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/master
<file_sep># Twitter Bot Workshop Welcome to the onboard.money twitter bot workshop! By then end of this workshop, you will have a fully operational twitter bot that interacts directly with ethereum. ![](https://i.imgur.com/hiHEYgn.png) As a part of this tutorial we will use the following tools: - onboard.money - typescript - graph protocol - twitter API - docker - redis - ethereum Ready? Lets jump into it! ## Twitter Project You'll need a twitter developer account to get started. In can take a few hours to get a new account approved so make sure to apply for it ASAP. You can add a link to this workshop in your application to accelerate the approval process. Once your account is active, create a new project and store your api keys somewhere safe. ## Clone this repository ```shell $ git clone https://github.com/onboardmoney/workshops.git $ cd workshops/twitter-bot/boilerplate $ yarn install ``` You are now in the root of the boilerplate project. This boilerplate is populated with all the boring twitter api, docker, and typescript setup. We start here so that we can focus on the fun ethereum stuff instead! To help you in the creation of your app, we've created an [example bot](https://twitter.com/treefarmerbot) built on top of [rDAI](https://rdai.money/) that allows anyone to start accumulating yield on their DAI and share the profit with charity. If you get lost at any point in the development process, take a peak at the [completed bot](https://github.com/onboardmoney/farmerbot) to see what a full implementation looks like. ## Installation Install dependencies ```bash yarn ``` Build the bot ```bash yarn bot build ``` Then, you'll need: * an onboard money application's API key. * a twitter developer account * optionally, a subgraph deployed on the graph protocol ## Getting the onboard.money application's API key You can run `npx onboardmoney` and follow the instructions. After registering and choosing your app's name, you'll get an API key and a relay address. You can checkout our [documentation page](https://docs.onboard.money) for a more detailed explanation ## Obtaining bot's credentials You'll need to create a dev account at the [Twitter Dev Portal](https://developer.twitter.com/). Once you got your dev account you'll need to create a Project. In the _Keys and tokens_ tab, under the _Consumer Key_ section you'll see the API key & secret created for your project, you'll also need to get and bearer token under _Authentication Tokens_. Back to the _Settings_ tab, you need to enable the 3rd party authentication and provide a callback URL. After you've done these steps you're almost ready to go, but first you need to set up your environment variables, and for that you should go to .env.example The `PORT` is where the bot will listen for incoming HTTP requests, 3000 by default. The `NETWORK` indicates on what network the bot will interact with. ```bash PORT=3000 NETWORK= ``` `OM_API_KEY` refers to the onboard money application API key you got earlier ```bash OM_API_KEY= ``` `API_KEY` and `API_KEY_SECRET` refers to your Twitter Project's keys. `AUTH_CALLBACK` should be the URL you configured in your twitter project, and it will handle the bot's account authentication. ```bash TWITTER_API_KEY= TWITTER_API_KEY_SECRET= TWITTER_V2_BEARER_TOKEN= TWITTER_AUTH_CALLBACK= ``` `BOT_NAME` is the account's name, this will be used to search for mentions. ```bash BOT_NAME= ``` If you already got your bot's account access token & secret you can put them in there, if not you can do it later. ```bash BOT_ACCESS_TOKEN= BOT_ACCESS_TOKEN_SECRET= ``` If you are planning to check for events in some network, we recommend using the Graph Protocol for that, and you can place your graph's name in here. ```bash SUBGRAPH_NAME= ``` After you configured these env variables, you need to rename .env.example to .env ```bash mv .env.example .env ``` And then run the bot by executing `sudo docker-compose up` This start the nestjs project, along with a redis instance. The bot consists has 3 _croned_ functions * search for tweets mentioning the bot, parse the tweets and store them in redis * pull parsed tweets from redis and process them one by one. * check for events in the network through the Graph Protocol. ## searching for tweets ## processing tweets ## checking for events The bot also has some endpoints: `/ping`: should always return a "pong" response. `/auth`: You can use this endpoint to authenticate your bot's account and obtain the bot's access token `/callback`: Twitter will redirect to this endpoint after you authorize your account. If the request is authentic, you'll get the bot's access token and secret, which you should put in your .env file. Then we have the following services: `auth.service`: it contains everything related to the twitter's oauth, no need to modify anything in here. `bot.service`: it contains the bot's logic. This boilerplate comes with two functions, which are scheduled to every minute, you can modify this by changing the cron time string in the @Cron decorator to whatever you see fit. `command.service`: it contains logic for the bot's commands `subgraph.service`: it contains logic for the bot's commands <file_sep>const addresses = { mainnet: { DAI: "0x6B175474E890<KEY>b954EedeAC495271d0F", }, kovan: { DAI: "0<KEY>", }, }; export default addresses; <file_sep>import { Injectable, Logger } from '@nestjs/common'; import Axios, { AxiosInstance } from "axios"; import Twitter from "twit"; import { Tweet } from './types'; import { DatabaseService } from './database/database.service'; @Injectable() export class TwitterService { axios: AxiosInstance; twit: Twitter constructor(private readonly db: DatabaseService) { this.axios = Axios.create({ baseURL: "https://api.twitter.com", headers: { "Authorization": "Bearer ".concat(process.env.TWITTER_V2_BEARER_TOKEN) } }) if (this.hasCredentials()) { this.twit = Twitter({ consumer_key: process.env.TWITTER_API_KEY, consumer_secret: process.env.TWITTER_API_KEY_SECRET, access_token: process.env.BOT_ACCESS_TOKEN, access_token_secret: process.env.BOT_ACCESS_TOKEN_SECRET }) } } hasCredentials() { const token = process.env.BOT_ACCESS_TOKEN const secret = process.env.BOT_ACCESS_TOKEN_SECRET return token != undefined && token.length > 0 && secret != undefined && secret.length > 0 } setCredentials(token: string, tokenSecret: string) { // ugly process.env.BOT_ACCESS_TOKEN = token process.env.BOT_ACCESS_TOKEN_SECRET = tokenSecret // create twitter instance with a fresh access token this.twit = Twitter({ consumer_key: process.env.TWITTER_API_KEY, consumer_secret: process.env.TWITTER_API_KEY_SECRET, access_token: token, access_token_secret: tokenSecret }) } public async getMentions(username: string, sinceTweet?: string): Promise<Tweet[]> { Logger.debug(`Fetching tweets since tweet: ${sinceTweet}`) // craft api call params const params = { query: "@" + username, expansions: "entities.mentions.username,author_id", } if (sinceTweet !== null) { params['since_id'] = sinceTweet } // pull tweets which mention the bot const { data } = await this.axios.get('/2/tweets/search/recent', { params }) const tweets = data.data if (tweets === undefined) return []; Logger.debug(`Got ${tweets.length} tweets`) // get users from every included user entity const users = data.includes.users.reduce((obj, item) => { return { ...obj, [item.id]: item.username } }, {}) // set the tweet's author's name return tweets.map((t) => { if (users[t.author_id] !== undefined) { t.author_name = users[t.author_id] } return t }) } public async reply(tweet: Tweet | string, message: string): Promise<any> { const tweetId = typeof (tweet) === 'string' ? tweet : tweet.id const params = { status: message, in_reply_to_status_id: tweetId, } return new Promise((resolve, reject) => { this.twit.post( 'statuses/update', params, (err, resp) => { if (err) { Logger.error(err) reject(err) } resolve(resp) } ) }) } public async sendDM(recepient: string, message: string): Promise<any> { const params = { "event": { "type": "message_create", "message_create": { "target": { "recipient_id": recepient }, "message_data": { "text": message } } } } return new Promise((resolve, reject) => { this.twit.post( 'direct_messages/events/new', params, (resp, err) => { if (err) { Logger.error(err) reject(err) } resolve(resp) } ) }) } } <file_sep>import { InfuraProvider } from '@ethersproject/providers'; import { Injectable, Logger, Inject } from '@nestjs/common'; import { App } from '@onboardmoney/sdk'; import { ethers, Contract, VoidSigner } from "ethers"; import addresses from "./contracts/addresses"; import abis from "./contracts/abis"; import { User, CommandContext, Tweet } from './types'; import { DatabaseService } from './database/database.service'; import { TwitterService } from './twitter.service'; @Injectable() export class CommandService { dai: Contract; constructor(private readonly db: DatabaseService, private readonly twitter: TwitterService, @Inject("ONBOARD_MONEY") private readonly onboardmoney: App) { // get provider const provider = new InfuraProvider(process.env.NETWORK, process.env.INFURA_ID); // init contracts this.dai = new ethers.Contract( addresses[process.env.NETWORK].DAI, abis.DAI, provider ); } async processCommand(user: User, tweet: Tweet, command: string, args: any[]): Promise<void> { const ctx = { user, tweet, command, args } switch (command) { default: Logger.warn(`Unknown command ${command} ${args}`) } } } <file_sep>import { Module } from '@nestjs/common'; import { ScheduleModule } from '@nestjs/schedule'; import { AppController } from './app.controller'; import { AuthService } from './auth.service'; import { BotService } from './bot.service'; import { DatabaseModule } from './database/database.module'; import { CommandService } from './command.service'; import { DatabaseService } from './database/database.service'; import { SubGraphService } from './subgraph.service'; import { App } from '@onboardmoney/sdk'; import { TwitterService } from './twitter.service'; @Module({ imports: [ DatabaseModule, ScheduleModule.forRoot() ], controllers: [AppController], providers: [AuthService, BotService, DatabaseService, CommandService, SubGraphService, TwitterService, { provide: 'ONBOARD_MONEY', useValue: new App(process.env.OM_API_KEY, `https://${process.env.NETWORK}.onboard.money`) }], }) export class AppModule { } <file_sep>require('dotenv').config() import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { readFileSync } from 'fs'; declare const module: any async function bootstrap() { const keyFile = readFileSync(process.env.PRIVATE_KEY_SSL_FILEPATH || 'ssl/localhost.key.pem') const certFile = readFileSync(process.env.CERTIFICATE_SSL_FILEPATH || 'ssl/localhost.crt.pem') const app = await NestFactory.create(AppModule, { httpsOptions: { key: keyFile, cert: certFile, }, logger: ['error', 'warn', 'debug'], }); await app.listen(process.env.PORT); if (module.hot) { module.hot.accept() module.hot.dispose(() => app.close()) } } bootstrap(); <file_sep>import { Injectable, OnModuleInit, Logger } from '@nestjs/common'; import { RedisService } from 'nestjs-redis'; import { Redis } from 'ioredis'; import { Tweet, User } from 'src/types'; import { TransactionReceipt } from '@onboardmoney/sdk'; const USER_KEY = userId => `user:${userId}` const TWEETS_KEY = 'tweets' const LAST_TWEET_ID_KEY = 'last_tweet_id' @Injectable() export class DatabaseService implements OnModuleInit { client: Redis; constructor(private readonly redisService: RedisService) { } async onModuleInit() { // TODO : is this really necessary? do we gain anything by storing the redis client? this.client = await this.getClient() } async getClient() { return this.redisService.getClient() } async createUser(userId: string, address: string): Promise<User> { const user = { userId, address } await this.client.set(USER_KEY(userId), JSON.stringify(user)) return user } async getUser(userId: string): Promise<any> { const user = await this.client.get(USER_KEY(userId)); return JSON.parse(user) } async addPendingTransfer(sender: string, tweetId: string) { Logger.debug(`Adding pending tranfer from: ${sender}`) return this.client.hset('pending_transfers', sender, tweetId) } async getPendingTransfers(): Promise<Record<string, string>> { return this.client.hgetall('pending_transfers') } async removePendingTransfer(sender: string): Promise<boolean> { Logger.debug(`Removing pending transfer from ${sender}`) const removed = await this.client.hdel('pending_transfers', sender) return removed > 0 } async addTweets(tweets: Tweet[]): Promise<void> { if (tweets === undefined || tweets.length === 0) return; const ids = tweets.map(t => t.id) // get lastest id from tweets // TODO : can i get this from the api's response? const lastId = ids.reduce((prev, current) => BigInt(current).valueOf() > BigInt(prev).valueOf() ? current : prev ) await Promise.all(tweets.map(t => { this.client.hset(TWEETS_KEY, t.id, JSON.stringify(t)) })) Logger.debug(`Tweets stored: ${tweets.length}`) Logger.debug(`Last tweet: ${lastId}`) await this.client.set(LAST_TWEET_ID_KEY, lastId) } async getLastTweetId(): Promise<string> { return this.client.get(LAST_TWEET_ID_KEY) } async getTweets(): Promise<Tweet[]> { const tweets = await this.client.hvals(TWEETS_KEY) return tweets.map(t => JSON.parse(t)) } async removeTweet(tweetId: string): Promise<any> { Logger.debug(`Deleting tweet ${tweetId}`) return this.client.hdel(TWEETS_KEY, tweetId) } } <file_sep>FROM node:14 as development ENV NODE_ENV=development WORKDIR /usr/src/app COPY package.json ./package.json COPY packages/bot/package.json ./packages/bot/package.json COPY packages/bot/dist/ ./packages/bot/dist/ RUN yarn install FROM node:14 as production ARG NODE_ENV=production ENV NODE_ENV=${NODE_ENV} WORKDIR /usr/src/app COPY package.json ./package.json COPY packages/bot/package.json ./packages/bot/package.json RUN yarn install --only=production COPY --from=development /usr/src/app/packages/bot/dist ./packages/bot/dist/ CMD ["node", "packages/bot/dist/main"]<file_sep>import { Injectable, Logger } from '@nestjs/common'; import { OAuth } from "oauth" @Injectable() export class AuthService { requestSecrets: { [token: string]: string} callbackUrl: string; oauth: OAuth; constructor() { this.oauth = new OAuth( 'https://api.twitter.com/oauth/request_token', 'https://api.twitter.com/oauth/access_token', process.env.TWITTER_API_KEY, process.env.TWITTER_API_KEY_SECRET, '1.0A', process.env.TWITTER_AUTH_CALLBACK, 'HMAC-SHA1' ); this.requestSecrets = {} } async getRequestToken(): Promise<string> { return new Promise((resolve, reject) => { Logger.debug(`Getting request token => ${process.env.TWITTER_AUTH_CALLBACK}`) this.oauth.getOAuthRequestToken(async (err, token, secret, results) => { // TODO : check the content of results if (err) reject(err) this.requestSecrets[token] = secret; resolve(`https://api.twitter.com/oauth/authorize?oauth_token=${token}`) }) }) } async getAccessToken(token, verifier): Promise<string[]> { const secret = this.requestSecrets[token] if (secret === undefined) throw Error(); return new Promise((resolve, reject) => { this.oauth.getOAuthAccessToken(token, secret, verifier, (err, token, secret) => { if (err) reject(err); resolve([token, secret]) }) }) } } <file_sep>import { Injectable, Logger, Inject } from '@nestjs/common'; import { Cron } from '@nestjs/schedule'; import { Tweet } from './types'; import { DatabaseService } from './database/database.service'; import { CommandService } from './command.service'; import { TwitterService } from './twitter.service'; @Injectable() export class BotService { name: string constructor(private readonly db: DatabaseService, private readonly commandService: CommandService, private readonly twitter: TwitterService) { this.name = process.env.BOT_NAME } @Cron(process.env.CRON_TIME || "0 * * * * *") async pullTweets() { // get tweets const tweets = await this.getTweets(); // parse them const parsedTweets = tweets.map(({ id, text, author_id, author_name, entities }) => { return { id, text, author_name, author: author_id, } }) Logger.debug(`Parsed tweets: ${parsedTweets.length}`) // store them in redis await this.db.addTweets(parsedTweets) } // TODO : make this configurable @Cron(process.env.CRON_TIME || "15 * * * * *") async process(): Promise<void> { if (!this.twitter.hasCredentials()) { Logger.warn(`You can't process tweets without credentials!`) return; } // get parsed tweets from redis const tweets = await this.db.getTweets() Logger.debug(`tweets to process: ${tweets.length}`) if (tweets.length === 0) return; for (const tweet of tweets) { await this.processTweet(tweet) await this.db.removeTweet(tweet.id) } } private async getTweets(): Promise<any[]> { const lastTweetId = await this.db.getLastTweetId(); return this.twitter.getMentions(this.name, lastTweetId) } async processTweet(tweet: Tweet): Promise<void> { const words = tweet.text.split(' ') // This only supports tweets like "@botname command arg1 arg2 ..." const [mention, command, ...args] = words; let user = await this.db.getUser(tweet.author) // process the command await this.commandService.processCommand(user, tweet, command, args) } } <file_sep>version: '3.8' services: bot: build: context: . target: development volumes: - /usr/src/app/dist - /usr/src/app/node_modules - .:/usr/src/app ports: - ${PORT}:${PORT} command: yarn bot start:dev env_file: - .env networks: - network depends_on: - redis redis: image: redis:5 networks: - network volumes: - ./data:/data networks: network: volumes: data: <file_sep>import { Module } from '@nestjs/common'; import { RedisModule } from 'nestjs-redis' import { DatabaseService } from './database.service'; @Module({ imports: [RedisModule.register({ url: 'redis://farmerbot.redis:6379', })], providers: [DatabaseService], }) export class DatabaseModule { } <file_sep>import { Controller, Get, Req, Res } from '@nestjs/common'; import { Request, Response } from 'express'; import { AuthService } from './auth.service'; import { TwitterService } from './twitter.service'; @Controller() export class AppController { constructor( private readonly twitterService: TwitterService, private readonly authService: AuthService) { } @Get("/ping") ping(): string { return "pong" } @Get('/twitter/auth') async auth(@Req() req: Request, @Res() res: Response) { const url = await this.authService.getRequestToken() res.redirect(url) } @Get("/twitter/callback") async callback(@Req() req: Request): Promise<any> { const { oauth_token, oauth_verifier } = req.query const [token, secret] = await this.authService.getAccessToken(oauth_token, oauth_verifier) this.twitterService.setCredentials(token, secret) return ` BOT_ACCESS_TOKEN=${token}<br /> BOT_ACCESS_TOKEN_SECRET=${secret}<br /> `; } } <file_sep>import DAI from "./abis/DAI.json"; const abis = { DAI, }; export default abis; <file_sep>import { Injectable, Logger } from '@nestjs/common'; import { DatabaseService } from './database/database.service'; import axios, { AxiosInstance } from "axios"; import { Cron } from '@nestjs/schedule'; import { CommandService } from './command.service'; @Injectable() export class SubGraphService { axiosInstance: AxiosInstance; constructor( private readonly db: DatabaseService, private readonly cmdService: CommandService ) { const url = "https://api.thegraph.com" this.axiosInstance = axios.create({ baseURL: url }); } @Cron(process.env.CRON_TIME || "45 * * * * *") async getTransfers() { const query = { query: `{ transfers { id from to value } }` } Logger.debug(`Pulling transfers`) const ret = await this.axiosInstance.post( `/subgraphs/name/${process.env.SUBGRAPH_NAME}`, query ) const { data } = ret; if (data === undefined) return; const { transfers } = data.data; // do something with the transfers } } <file_sep>export interface Tweet { id: string; text: string; author: string; author_name: string; } export interface User { userId: string; address: string; } export interface CommandContext { user: User; tweet: Tweet; command: string; args: any[]; }
c93fbd04c5c2fc207f8cf8f9c6b4e5fc44d8113b
[ "Markdown", "TypeScript", "Dockerfile", "YAML" ]
16
Markdown
onboardmoney/workshops
b3794bc3e65549728a445975b3943365aee7cc81
36087407ef58002b463330f6b45349269c061758
refs/heads/master
<file_sep>#!/bin/bash # Set /etc/apt/sources.list mkdir -p /etc/apt cat <<EOF >/etc/apt/sources.list deb http://deb.openswitch.net/ unstable main opx opx-non-free deb http://httpredir.debian.org/debian/ jessie main contrib non-free deb-src http://httpredir.debian.org/debian/ jessie main contrib non-free deb http://httpredir.debian.org/debian/ jessie-backports main contrib non-free deb-src http://httpredir.debian.org/debian/ jessie-backports main contrib non-free deb http://httpredir.debian.org/debian/ jessie-updates main contrib non-free deb-src http://httpredir.debian.org/debian/ jessie-updates main contrib non-free deb http://security.debian.org/ jessie/updates main contrib non-free deb-src http://security.debian.org/ jessie/updates main contrib non-free EOF # get deb.openswitch.net gpg key apt-key adv --keyserver pgp.mit.edu --recv AD5073F1 || \ apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys AD5073F1 apt-get update
85488a30971c4892583d62353610ce4f9c7fa853
[ "Shell" ]
1
Shell
adobush/opx-onie-installer
6f9956b9395953442ea51ada5117275293576efa
d9697a94ebdc1df49ea85e6dafcc0f7d4ba0d597
refs/heads/master
<repo_name>lsdlabs/FavoriteThings<file_sep>/FavoriteThings/FavoriteThings/FavoriteThingsViewController.swift // // ViewController.swift // FavoriteThings // // Created by <NAME> on 8/27/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class FavoriteThingsViewController: UITableViewController { var favoriteThingsItems = ["Sleeping", "Eating", "Laughter", "Sleeping", "Eating"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return favoriteThingsItems.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "FavoriteThingsItem", for: indexPath) cell.textLabel?.text = favoriteThingsItems[indexPath.row] return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let cell = tableView.cellForRow(at: indexPath) { if cell.accessoryType == .none { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } } tableView.deselectRow(at: indexPath, animated: true) } func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool { return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { favoriteThingsItems.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } // func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) { // if (editingStyle == UITableViewCellEditingStyle.delete) { // // handle delete (by removing the data from your array and updating the tableview) // if let tv=tableView // { // favoriteThingsItems.removeAtIndex(indexPath!.row) // tv.deleteRows(at: [indexPath as IndexPath], with: .fade) // } // // // } // } }
b6c5800fd1361b4c8761911b7479be63ba2869ac
[ "Swift" ]
1
Swift
lsdlabs/FavoriteThings
f87e28cd466277f16256c2f0e14e4ecec86cc870
83959b4280435053d19899ad9a11f51c97e6b349
refs/heads/master
<repo_name>yashesh001/PremiumCalculator<file_sep>/Calculators/Controllers/ManageOccupationController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Calculators.Controllers { public class ManageOccupationController : Controller { // GET: /ManageOccupation/ public ActionResult Index() { return View(); } public ActionResult AddOccupation() { return PartialView("_AddOccupation"); } public ActionResult ShowAllOccupations() { return PartialView("_ShowAllOccupations"); } public ActionResult ShowAllOccupationRatings() { var ratingsController = new OccupationsRatingController(); return View("ShowAllOccupationRatings", ratingsController.GetOccupationRatings()); } public ActionResult EditOccupation() { return PartialView("_EditOccupation"); } public ActionResult DeleteOccupation() { return PartialView("DeleteOccupation"); } } }<file_sep>/Calculators/Controllers/MonthlyPremiumController.cs using Calculators.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Calculators.Controllers { public class MonthlyPremiumController : Controller { // GET: /MonthlyPremium/ public ActionResult Index() { var model = new MonthlyCalculateModel(); return View(model); } public ActionResult CalculatePremium() { return PartialView("_Calculate"); } public JsonResult GetOccupations() { var occupationController = new OccupationsController(); var OccupationList = occupationController.GetOccupations(); return this.Json(OccupationList, JsonRequestBehavior.AllowGet); } } }<file_sep>/README.md # PremiumCalculator Developed with AngularJS as front end, WebAPI and .Net technologies The application is a mix of AngularJS implementation to Add / View / Delete occupations while MVC and JQuery implementation of Calculate Premium. Tools and Technologies used : .Net framework 4.5 Visual Studio 2013 JQuery AngularJS Entity Framework WebAPI template from Visual Studio 2013 Microsoft SQL server - Local database This project can be extended by using any currently available dependency injection techniques e.g. Ninject or any other components. This can be helpful in resolving other functionalities like logging etc. Repository pattern should be implemented for datasets in order to make the implementation extendable for unit testing. To Use: Calculate monthly premium can be used from main page straight away - HomeController/Index To Configure Occupations, user can register using the login page and after login, the user can use the available options of Add / Show all and Delete features for Occupations. The configured data is stored on a local database. <file_sep>/Calculators/Controllers/PremiumCalculatorController.cs using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Description; using Calculators.Data; namespace Calculators.Controllers { public class PremiumCalculatorController : ApiController { private PremiumsDbEntities db = new PremiumsDbEntities(); // GET api/PremiumCalculator public IQueryable<CalculatorLog> GetCalculatorLogs() { return db.CalculatorLogs; } // GET api/PremiumCalculator/5 [ResponseType(typeof(CalculatorLog))] public IHttpActionResult GetCalculatorLog(int id) { CalculatorLog calculatorlog = db.CalculatorLogs.Find(id); if (calculatorlog == null) { return NotFound(); } return Ok(calculatorlog); } // PUT api/PremiumCalculator/5 public IHttpActionResult PutCalculatorLog(int id, CalculatorLog calculatorlog) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != calculatorlog.Id) { return BadRequest(); } db.Entry(calculatorlog).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!CalculatorLogExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); } // POST api/PremiumCalculator [ResponseType(typeof(CalculatorLog))] public IHttpActionResult PostCalculatorLog(CalculatorLog calculatorlog) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.CalculatorLogs.Add(calculatorlog); db.SaveChanges(); return CreatedAtRoute("DefaultApi", new { id = calculatorlog.Id }, calculatorlog); } // DELETE api/PremiumCalculator/5 [ResponseType(typeof(CalculatorLog))] public IHttpActionResult DeleteCalculatorLog(int id) { CalculatorLog calculatorlog = db.CalculatorLogs.Find(id); if (calculatorlog == null) { return NotFound(); } db.CalculatorLogs.Remove(calculatorlog); db.SaveChanges(); return Ok(calculatorlog); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool CalculatorLogExists(int id) { return db.CalculatorLogs.Count(e => e.Id == id) > 0; } } }<file_sep>/Calculators/Models/MonthlyCalculateModel.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; namespace Calculators.Models { public class MonthlyCalculateModel { [Required] public string Name { get; set; } [Required] [DataType(DataType.Date)] public DateTime DateOfBirth { get; set; } public int Age { get; set; } [Required] public int SumInsured { get; set; } public string Occupation { get; set; } public IEnumerable<SelectListItem> Occupations { get; set; } public double Premium { get; set; } } }<file_sep>/Calculators/Controllers/HomeController.cs using Calculators.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; namespace Calculators.Controllers { public class HomeController : Controller { public ActionResult Index() { var model = new MonthlyCalculateModel(); var occupationController = new OccupationsController(); model.Occupations = occupationController.GetOccupations().Select(item => new SelectListItem() { Text = item.Name, Value = item.Factor.ToString() }); model.SumInsured = 100000; model.DateOfBirth = DateTime.Now.Date; return View(model); } } } <file_sep>/Calculators/MyScripts/Services.js app.service("OccupationCRUDService", function ($http) { //Read all Occupations this.getOccupations = function () { return $http.get("/api/Occupations"); }; //Read all Occupations Ratings this.getRatings = function () { return $http.get("/api/OccupationsRating"); }; //Read Occupation by Id this.getOccupation = function (id) { return $http.get("/api/Occupations/" + id); }; //Function to create new Occupation this.post = function (Occupation) { var request = $http({ method: "post", url: "/api/Occupations", data: Occupation }); return request; }; //Edit Occupation By ID this.put = function (id, Occupation) { var request = $http({ method: "put", url: "/api/Occupations/" + id, data: Occupation }); return request; }; //Delete Occupation By ID this.delete = function (id) { var request = $http({ method: "delete", url: "/api/Occupations/" + id }); return request; }; });<file_sep>/Calculators/MyScripts/Module.js var app = angular.module("ApplicationModule", ["ngRoute"]); app.factory("ShareData", function () { return { value: 0 } }); //Showing Routing app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) { $routeProvider.when('/showOccupations', { templateUrl: 'ManageOccupation/ShowAllOccupations', controller: 'ShowOccupationsController' }); $routeProvider.when('/showRatings', { templateUrl: 'ManageOccupation/ShowAllRatings', controller: 'ShowRatingsController' }); $routeProvider.when('/addOccupation', { templateUrl: 'ManageOccupation/AddOccupation', controller: 'AddOccupationsController' }); $routeProvider.when("/editOccupation", { templateUrl: 'ManageOccupation/EditOccupation', controller: 'EditOccupationsController' }); $routeProvider.when('/deleteOccupation', { templateUrl: 'ManageOccupation/DeleteOccupation', controller: 'DeleteOccupationsController' }); $routeProvider.otherwise( { redirectTo: '/' }); $locationProvider.html5Mode({ enabled: true, requireBase: false }); //$locationProvider.html5Mode(true).hashPrefix('!') }]);<file_sep>/Calculators/Controllers/OccupationsRatingController.cs using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Description; using Calculators.Data; namespace Calculators.Controllers { public class OccupationsRatingController : ApiController { private PremiumsDbEntities db = new PremiumsDbEntities(); // GET api/OccupationsRating public IQueryable<OccupationRating> GetOccupationRatings() { return db.OccupationRatings; } // GET api/OccupationsRating/5 [ResponseType(typeof(OccupationRating))] public IHttpActionResult GetOccupationRating(int id) { OccupationRating occupationrating = db.OccupationRatings.Find(id); if (occupationrating == null) { return NotFound(); } return Ok(occupationrating); } // PUT api/OccupationsRating/5 public IHttpActionResult PutOccupationRating(int id, OccupationRating occupationrating) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != occupationrating.Id) { return BadRequest(); } db.Entry(occupationrating).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!OccupationRatingExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); } // POST api/OccupationsRating [ResponseType(typeof(OccupationRating))] public IHttpActionResult PostOccupationRating(OccupationRating occupationrating) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.OccupationRatings.Add(occupationrating); db.SaveChanges(); return CreatedAtRoute("DefaultApi", new { id = occupationrating.Id }, occupationrating); } // DELETE api/OccupationsRating/5 [ResponseType(typeof(OccupationRating))] public IHttpActionResult DeleteOccupationRating(int id) { OccupationRating occupationrating = db.OccupationRatings.Find(id); if (occupationrating == null) { return NotFound(); } db.OccupationRatings.Remove(occupationrating); db.SaveChanges(); return Ok(occupationrating); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool OccupationRatingExists(int id) { return db.OccupationRatings.Count(e => e.Id == id) > 0; } } }<file_sep>/Calculators/MyScripts/AddOccupationsController.js app.controller('AddOccupationsController', function ($scope, OccupationCRUDService) { $scope.ID = 0; $scope.save = function () { var Occupation = { //ID: $scope.ID, OccupationName: $scope.OccupationName, RatingId: $scope.RatingId, }; var promisePost = OccupationCRUDService.post(Occupation); promisePost.then(function (pl) { alert("Occupation Saved Successfully."); }, function (errorPl) { $scope.error = 'failure loading Occupation', errorPl; alert(errorPl); }); }; });<file_sep>/Calculators/MyScripts/DeleteOccupationsController.js app.controller("DeleteOccupationsController", function ($scope, $location, ShareData, OccupationCRUDService) { getOccupation(); function getOccupation() { var promiseGetOccupation = OccupationCRUDService.getOccupation(ShareData.value); promiseGetOccupation.then(function (pl) { $scope.Occupation = pl.data; }, function (errorPl) { $scope.error = 'Failure loading Occupation', errorPl; alert('Failure loading Occupation'); }); } $scope.delete = function () { var promiseDeleteOccupation = OccupationCRUDService.delete(ShareData.value); promiseDeleteOccupation.then(function (pl) { $location.path("/showOccupations"); }, function (errorPl) { $scope.error = 'failure loading Occupation', errorPl; }); }; });<file_sep>/Calculators/Models/OccupationModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Calculators.Models { [Serializable] public class OccupationModel { public int Id { get; set; } public string Name { get; set; } public string Rating { get; set; } public double Factor { get; set; } } }
b9cc22cf49ce83bc276cce3a42b83225b9d69f54
[ "Markdown", "C#", "JavaScript" ]
12
C#
yashesh001/PremiumCalculator
2840aeef544f4661c3f59312c695225bb566811a
e1d23957fd5467881b3a39167357a0af1065e4b4
refs/heads/master
<file_sep>import modalWin from './start'; import './style/main.scss'; class MoleGame { constructor() { this.holes = document.querySelectorAll('.hole'); this.scoreBoard = document.querySelector('.score'); this.moles = document.querySelectorAll('.mole'); this.modalFinish = document.querySelector('.js-win'); this.lastHole = ''; this.score = 0; this.timeUp = false; } randomTime(min, max) { return Math.round(Math.random() * (max - min) + min); } randomHole(holes) { const idx = Math.floor(Math.random() * holes.length); const hole = this.holes[idx]; if (hole === this.lastHole) { return this.randomHole(holes); } this.lastHole = hole; return hole; } finish(time) { setTimeout(() => { this.timeUp = true; this.modalFinish.classList.remove('close'); }, time); } handleBonk() { this.moles.forEach((mole) => mole.addEventListener('click', function(e) { if (!e.isTrusted) return; updateScore(); this.classList.remove('up'); })); const updateScore = () => { this.scoreBoard.textContent++; } } peep() { const time = this.randomTime(200, 1000); const hole = this.randomHole(this.holes); hole.classList.add('up'); setTimeout(() => { hole.classList.remove('up'); if (!this.timeUp) this.peep(); this.finish(10000); }, time); } start() { this.randomHole(this.holes); this.handleBonk(); this.peep(); } } const game = new MoleGame(); modalWin(game); <file_sep># Whack-a-Mole-Game- Whack-a-Mole Game <file_sep> const modalWin = (game) => { var btnStart = document.querySelector('.js-start'), modalWin = document.querySelector('.js-modal'); btnStart.addEventListener('click', () => { modalWin.classList.add('close'); game.start(); }); } export default modalWin;
05a2acdd28c872e53b03efa22488889052e21e8d
[ "JavaScript", "Markdown" ]
3
JavaScript
frontmaker/Whack-a-Mole-Game-
5795275f40eaf9b995de31d84cb39e8d82b9a06d
362737b256469e15f10f986bdb78428445be22e0
refs/heads/master
<repo_name>bobweston/docker-images<file_sep>/yeoman/README.md Based on Ubuntu 16.04 LTS Xenial Run the latest container with: `docker run stakater/yeoman` `docker run --name yeoman -d -v $PWD:/home/stakater -t stakater/yeoman` Build an image: `docker build -t stakater/yeoman .` Push an image: `sudo docker push stakater/yeoman` _Note_ you might have to login first before you can push the image to docker-hub `sudo docker login` Its important to read this documentation: https://github.com/phusion/baseimage-docker `docker exec -it <CONTAINER-NAME> bash` to verify the version: `node --version && npm --version && yo --version` once you are inside the container then switch user to `stakater` as otherwise you might get strange permission errors like following: ``` root@576a9fe8054c:/home/stakater# yo -h /usr/lib/node_modules/yo/node_modules/configstore/index.js:53 throw err; ^ Error: EACCES: permission denied, open '/root/.config/configstore/insight-yo.json' You don't have access to this file. at Error (native) at Object.fs.openSync (fs.js:549:18) at Object.fs.readFileSync (fs.js:397:15) at Object.create.all.get (/usr/lib/node_modules/yo/node_modules/configstore/index.js:34:26) at Object.Configstore (/usr/lib/node_modules/yo/node_modules/configstore/index.js:27:44) at new Insight (/usr/lib/node_modules/yo/node_modules/insight/lib/index.js:37:34) at Object.<anonymous> (/usr/lib/node_modules/yo/lib/cli.js:172:11) at Module._compile (module.js:409:26) at Object.Module._extensions..js (module.js:416:10) at Module.load (module.js:343:32) ``` to switch user run `su - stakater` <file_sep>/gradle/README.md ## gradle docker images based on Ubuntu 14.04 and Oracle Java 8 Run the latest container with: `docker run stakater/gradle` ## Advanced Build an image: `docker build -t stakater/gradle .` Push an image: `sudo docker push stakater/gradle` _Note_ you might have to login first before you can push the image to docker-hub `sudo docker login`<file_sep>/filebeat/Dockerfile FROM stakater/base MAINTAINER <NAME> <<EMAIL>> RUN apt-get update && \ apt-get install -yq --no-install-recommends wget pwgen ca-certificates && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* RUN curl -L -O https://download.elastic.co/beats/filebeat/filebeat_1.2.1_amd64.deb RUN dpkg -i filebeat_1.2.1_amd64.deb COPY docker-entrypoint.sh /docker-entrypoint.sh COPY filebeat.yml /etc/filebeat/filebeat.yml ENTRYPOINT ["/docker-entrypoint.sh"] RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* CMD ["/usr/bin/filebeat", "-c", "/etc/filebeat/filebeat.yml"]<file_sep>/gocd-agent/README.md ## GoCD Agent 16.5.0-3305 GoCD Agent docker file with `jq`, `awscli` and `terraform` installed <file_sep>/logstash/Dockerfile FROM stakater/java:oracle-8 MAINTAINER <NAME> <<EMAIL>> RUN apt-get update && \ apt-get install -yq --no-install-recommends wget pwgen ca-certificates && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* # grab gosu for easy step-down from root ENV GOSU_VERSION 1.7 RUN set -x \ && wget -O /usr/local/bin/gosu "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$(dpkg --print-architecture)" \ && wget -O /usr/local/bin/gosu.asc "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$(dpkg --print-architecture).asc" \ && export GNUPGHOME="$(mktemp -d)" \ && gpg --keyserver ha.pool.sks-keyservers.net --recv-keys <KEY> \ && gpg --batch --verify /usr/local/bin/gosu.asc /usr/local/bin/gosu \ && rm -r "$GNUPGHOME" /usr/local/bin/gosu.asc \ && chmod +x /usr/local/bin/gosu \ && gosu nobody true # Set default Logstash version ENV LOGSTASH_VERSION 2.3.1-1_all RUN wget https://download.elastic.co/logstash/logstash/packages/debian/logstash_${LOGSTASH_VERSION}.deb -O /tmp/logstash.deb && \ dpkg -i /tmp/logstash.deb ; \ apt-get -f -y install && \ rm -rf /tmp/logstash.deb && \ /opt/logstash/bin/plugin install logstash-input-beats && \ /opt/logstash/bin/plugin install logstash-filter-grok && \ /opt/logstash/bin/plugin install logstash-output-elasticsearch && \ /opt/logstash/bin/plugin install logstash-output-email && \ /opt/logstash/bin/plugin install logstash-output-hipchat ENV PATH /opt/logstash/bin:$PATH COPY docker-entrypoint.sh / ENTRYPOINT ["/docker-entrypoint.sh"] CMD ["logstash", "agent"] <file_sep>/tomcat/filebeat/Dockerfile FROM stakater/tomcat:8 MAINTAINER hazim1093 <<EMAIL>> RUN apt-get update && \ apt-get install -yq --no-install-recommends wget pwgen ca-certificates supervisor && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* RUN mkdir -p /var/log/supervisor # supervisor base configuration COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf RUN curl -L -O https://download.elastic.co/beats/filebeat/filebeat_1.2.1_amd64.deb RUN dpkg -i filebeat_1.2.1_amd64.deb COPY docker-entrypoint.sh /docker-entrypoint.sh RUN sudo chmod +x /docker-entrypoint.sh COPY filebeat.yml /etc/filebeat/filebeat.yml RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* EXPOSE 8080 ENTRYPOINT ["/docker-entrypoint.sh"] # default command CMD ["/usr/bin/supervisord"]<file_sep>/tomcat/filebeat/README.md ## Tomcat 8 Docker image with Filebeat Tomcat 8 Docker image with filebeat to beat logs of tomcat<file_sep>/kairosdb/README.md # KairosDB Docker Dockerfile to run KairosDB on Cassandra. Configuration is done through environment variables. `docker run stakater/kairosdb` `docker run -P -e "CASS_HOSTS=192.168.1.63:9160" -e "REPFACTOR=1" stakater/kairosdb` ## Advanced ### Simple! ./build.sh Build an image: `docker build -t stakater/kairosdb .` Push an image: `sudo docker push stakater/kairosdb` _Note_ you might have to login first before you can push the image to docker-hub `sudo docker login` ## Healthcheck There are currently two health checks executed for each API. - The JVM thread deadlock check verifies that no deadlocks exist in the KairosDB JVM. - The Datastore query check performs a query on the data store to ensure that the data store is responding. KairosDB provides REST APIs that show the health of the system. See [HealthCheck](https://kairosdb.github.io/docs/build/html/restapi/Health.html) ### Status http://[host]:[port]/api/v1/health/status [ "JVM-Thread-Deadlock: OK", "Datastore-Query: OK" ] ### Check Checks the status of each health check. If all are healthy it returns status 204 otherwise it returns 500. This can be configured to return something other than 204 by changing the kairosdb.health.healthyResponseCode property. Method GET Request http://[host]:[port]/api/v1/health/check Response Success Returns 204 if all checks are healthy. Failure Returns 500 if any of the checks are unhealthy. ## [Web UI](https://kairosdb.github.io/docs/build/html/WebUI.html) http://[host]:[port] <file_sep>/nginx-prerender/Dockerfile # This docker images is a combination of nginx (official) & stakater/prerender FROM node:6 MAINTAINER hazim1093 <<EMAIL>> ENV NGINX_VERSION 1.11.5-1~jessie RUN apt-key adv --keyserver hkp://pgp.mit.edu:80 --recv-keys <KEY> \ && echo "deb http://nginx.org/packages/mainline/debian/ jessie nginx" >> /etc/apt/sources.list \ && apt-get update \ && apt-get install --no-install-recommends --no-install-suggests -y \ ca-certificates \ nginx=${NGINX_VERSION} \ nginx-module-xslt \ nginx-module-geoip \ nginx-module-image-filter \ nginx-module-perl \ nginx-module-njs \ gettext-base \ && apt-get install -y vim git supervisor \ && rm -rf /var/lib/apt/lists/* # forward NGINX request and error logs to docker log collector RUN ln -sf /dev/stdout /var/log/nginx/access.log \ && ln -sf /dev/stderr /var/log/nginx/error.log # create supervisor log directory and Prerenderer app directory RUN mkdir -p /var/log/supervisor && \ mkdir -p /usr/src/app WORKDIR /usr/src/app RUN git clone https://github.com/prerender/prerender.git && cd prerender && npm install ENV PORT=1337 # supervisor base configuration COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf # NGINX and Prerenderer ports EXPOSE 80 443 1337 # default command CMD ["/usr/bin/supervisord"]<file_sep>/dockup/run.sh #!/bin/bash if [[ "$RESTORE" == "true" ]]; then ./restore.sh else if [ -n "$CRON_TIME" ]; then env | grep -v 'affinity:container' | sed -e 's/^\([^=]*\)=\(.*\)/export \1="\2"/' > /env.conf # Save current environment echo "${CRON_TIME} . /env.conf && /backup.sh 2>&1 | logger -t dockup-cron-${BACKUP_NAME}" > /crontab.conf crontab /crontab.conf echo "=> Running dockup backups as a cronjob for ${CRON_TIME}" exec cron -f else ./backup.sh fi fi<file_sep>/dockup/restore.sh #!/bin/bash if [ ! -n "${LAST_BACKUP}" ]; then # Find last backup file : ${LAST_BACKUP:=$(aws s3 --region $AWS_DEFAULT_REGION ls s3://$S3_BUCKET_NAME | awk -F " " '{print $4}' | grep ^$BACKUP_NAME | sort -r | head -n1)} fi # Download backup from S3 aws s3 --region $AWS_DEFAULT_REGION cp s3://$S3_BUCKET_NAME/$LAST_BACKUP $LAST_BACKUP || (echo "Failed to download tarball from S3"; exit) # Extract backup tar xzf $LAST_BACKUP $RESTORE_TAR_OPTION || exit # If a post extraction command is defined, run it if [ -n "$AFTER_RESTORE_CMD" ]; then eval "$AFTER_RESTORE_CMD" || exit fi <file_sep>/nginx/with-consul-template/Dockerfile FROM stakater/nginx:latest MAINTAINER <NAME> <<EMAIL>> # setting a default value to make it work on dockerhub ARG CONSUL_TEMPLATE_VERSION=0.16.0 # remove all default configurations from Nginx # RUN rm -v /etc/nginx/conf.d/*.conf # we define an environment variable with the location of our Consul cluster. By default, it will try to resolve to # consul:8500 which would be the behavior if we have Consul running as a container in the same host and we link it to this # Nginx container (with the alias consul, of course). But this environment variable can also be overridden when we run the # container if we want to point somewhere else. ENV CONSUL_URL consul:8500 # download the latest version of Consul Template and we put it on /usr/local/bin ADD https://releases.hashicorp.com/consul-template/${CONSUL_TEMPLATE_VERSION}/consul-template_${CONSUL_TEMPLATE_VERSION}_linux_amd64.zip /usr/bin/ RUN unzip /usr/bin/consul-template_${CONSUL_TEMPLATE_VERSION}_linux_amd64.zip # we define a volume /templates, which is where we will mount our template files from the host. This way we can reuse # the same image for different services and templates. VOLUME /templates # add the start up script (which is used as the entrypoint to our containers) ADD start.sh /bin/start.sh # our container will expose port 80, where Nginx will be listening for new connections EXPOSE 80 # entrypoint will be the /bin/start.sh ENTRYPOINT ["/bin/start.sh"]<file_sep>/kairosdb/build.sh #!/bin/bash _kairosdb_version=$1 _kairosdb_tag=$2 _release_build=false if [ -z "${_kairosdb_version}" ]; then source KAIROSDB_VERSION _kairosdb_version=$KAIROSDB_VERSION _kairosdb_tag=$KAIROSDB_VERSION _release_build=true fi echo "KAIROSDB_VERSION: ${_kairosdb_version}" echo "DOCKER TAG: ${_kairosdb_tag}" echo "RELEASE BUILD: ${_release_build}" docker build --build-arg KAIROSDB_VERSION=${_kairosdb_version} --tag "stakater/kairosdb:${_kairosdb_tag}" --no-cache=true . if [ $_release_build == true ]; then docker build --build-arg KAIROSDB_VERSION=${_kairosdb_version} --tag "stakater/kairosdb:latest" --no-cache=true . fi <file_sep>/base/README.md ## Base Docker Image Run the latest container with: `docker run stakater/base` ## Advanced Build an image: `docker build -t stakater/base .` Push an image: `sudo docker push stakater/base` _Note_ you might have to login first before you can push the image to docker-hub `sudo docker login` Its important to read this documentation: https://github.com/phusion/baseimage-docker<file_sep>/logstash/README.md ## logstash docker image based on Ubuntu 14.04 & oracle java 8 Run the latest container with: `docker run stakater/logstash` ## Advanced Build an image: `docker build -t stakater/logstash .` Push an image: `sudo docker push stakater/logstash` _Note_ you might have to login first before you can push the image to docker-hub `sudo docker login` Start Logstash with configuration file If you need to run logstash with a configuration file, logstash.conf, that's located in your current directory, you can use the logstash image as follows: run logstash which will take input from stdin & send output to stdout `docker run -it --rm stakater/logstash logstash -e 'input { stdin { } } output { stdout { } }'` Tell logstash container three things: 1. ports to expose 2. logstash conf 3. `docker run -it --rm -v "$PWD":/config-dir -p 5044:5044 stakater/logstash logstash -f /config-dir/logstash.conf` it should print: ``` Settings: Default pipeline workers: 1 Pipeline main started ``` `$ docker run -it --rm -v "$PWD":/config-dir logstash logstash -f /config-dir/logstash.conf` logstash configurations can be found on this location: /etc/logstash/conf.d one beats input: beats-input.conf one elasticsearch output: 30-output.conf Logstash has a rich collection of input, filter, codec and output plugins. Input Plugins - https://www.elastic.co/guide/en/logstash/current/input-plugins.html An input plugin enables a specific source of events to be read by Logstash. Filter Plugins - https://www.elastic.co/guide/en/logstash/current/filter-plugins.html A filter plugin performs intermediary processing on an event. Filters are often applied conditionally depending on the characteristics of the event. Output Plugins - https://www.elastic.co/guide/en/logstash/current/output-plugins.html An output plugin sends event data to a particular destination. Outputs are the final stage in the event pipeline. Codec Plugins - https://www.elastic.co/guide/en/logstash/current/codec-plugins.html A codec plugin changes the data representation of an event. Codecs are essentially stream filters that can operate as part of an input or output. Inspiration from: https://hub.docker.com/_/logstash/ manage_template => false index => "%{[@metadata][beat]}-%{+YYYY.MM.dd}" document_type => "%{[@metadata][type]}" <file_sep>/yeoman/Dockerfile FROM phusion/baseimage:0.9.19 MAINTAINER <NAME> <<EMAIL>> RUN echo "deb http://archive.ubuntu.com/ubuntu xenial main universe" > /etc/apt/sources.list RUN apt-get -y update RUN apt-get -y install sudo nano git sudo zip bzip2 fontconfig wget RUN echo 'root:stakater' |chpasswd RUN groupadd stakater && useradd stakater -s /bin/bash -m -g stakater -G stakater && adduser stakater sudo RUN echo 'stakater:stakater' |chpasswd RUN cd /home && chown -R stakater:stakater /home/stakater # install NodeJs RUN curl -sL https://deb.nodesource.com/setup_4.x | sudo bash - RUN apt-get update RUN apt-get -y install nodejs # install yeoman RUN npm -g install npm RUN npm install -g yo RUN npm install -g generator-generator RUN \ # fix stakater user permissions chown -R stakater:stakater \ /home/stakater \ /usr/lib/node_modules && \ # cleanup apt-get clean && \ rm -rf /var/lib/apt/lists/* \ /tmp/* \ /var/tmp/*<file_sep>/swagger-editor/Dockerfile FROM stakater/tomcat:8 MAINTAINER <NAME> <<EMAIL>> # Use baseimage-docker's init system. CMD ["/sbin/my_init"] ENV SWAGGER_EDITOR_VERSION v2.9.8 # make sure the package repository is up to date RUN echo "deb http://archive.ubuntu.com/ubuntu trusty main universe" > /etc/apt/sources.list RUN apt-get -y update # install http-server WORKDIR /tomcat RUN rm -Rf webapps/* RUN wget https://github.com/swagger-api/swagger-editor/releases/download/${SWAGGER_EDITOR_VERSION}/swagger-editor.zip RUN mv *.zip webapps/ROOT.war # Clean up APT when done. RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*<file_sep>/monitoring/README.md Grafana KairosDB Cassandra ========================== This docker compose runs KairosDB, Cassandra & Grafana which is a perfect combo for stats monitoring! docker-compose -f cassandra-kairosdb-grafana.yml up ## KairosDB ### KairosDB Health Check http://[host]:[port]/api/v1/health/check ### KairosDB Status http://[host]:[port]/api/v1/health/status ### Open KairosDB [Web UI](https://kairosdb.github.io/docs/build/html/WebUI.html) http://[host]:[port] ## Check Grafana http://[host]:[port]/ _NOTE_ Look in the README's of individual components for further details.<file_sep>/grails/2.3.8/README.md ## Base Docker Image based on Ubuntu 14.04 and Oracle Java 8 Run the latest container with: `docker run stakater/grails:2.3.8` OR `docker run --name stakater_grails --rm -i -t stakater/grails:2.3.8 bash` This will create a container named stakater_grails and start a Bash session. ## Advanced Build an image: `docker build -t stakater/grails:2.3.8 .` Push an image: `sudo docker push stakater/grails:2.3.8` _Note_ you might have to login first before you can push the image to docker-hub `sudo docker login`<file_sep>/java/oracle/oracle-6/README.md ## Base Docker Image Run the latest container with: `docker run stakater/java:oracle-6` ## Advanced Build an image: `docker build -t stakater/java:oracle-6 .` Push an image: `sudo docker push stakater/java:oracle-6` _Note_ you might have to login first before you can push the image to docker-hub `sudo docker login`<file_sep>/swagger-editor/README.md ## swagger editor https://github.com/swagger-api/swagger-editor based on Ubuntu 14.04 Run the latest container with: `docker run -d -p 8080:8080 -t stakater/swagger-editor` ## Advanced Build an image: `docker build -t stakater/swagger-editor .` Push an image: `sudo docker push stakater/swagger-editor` _Note_ you might have to login first before you can push the image to docker-hub `sudo docker login` you can access the swagger-editor at: `http://localhost:8080/swagger-editor/#/`<file_sep>/java/oracle/oracle-8/README.md ## Base Docker Image based on Ubuntu 14.04 Run the latest container with: `docker run stakater/java:oracle-8` ## Advanced Build an image: `docker build -t stakater/java:oracle-8 .` Push an image: `sudo docker push stakater/java:oracle-8` _Note_ you might have to login first before you can push the image to docker-hub `sudo docker login`<file_sep>/kibana/README.md How to use this image You can run the default kibana command simply: $ docker run --link some-elasticsearch:elasticsearch -d kibana You can also pass in additional flags to kibana: $ docker run --link some-elasticsearch:elasticsearch -d kibana --plugins /somewhere/else This image includes EXPOSE 5601 (default port). If you'd like to be able to access the instance from the host without the container's IP, standard port mappings can be used: $ docker run --name some-kibana --link some-elasticsearch:elasticsearch -p 5601:5601 -d kibana You can also provide the address of elasticsearch via ELASTICSEARCH_URL environnement variable: $ docker run --name some-kibana -e ELASTICSEARCH_URL=http://some-elasticsearch:9200 -p 5601:5601 -d kibana Then, access it via http://localhost:5601 or http://host-ip:5601 in a browser. docker run --name pliro-kibana -e ELASTICSEARCH_URL=http://192.168.99.100:9200 -p 5601:5601 -d kibana <file_sep>/kairosdb/test/kairos_test.sh #!/bin/bash curl -X POST -d @kairos_write.txt http://<kairos-ip>:8080/api/v1/datapoints --header "Content-Type:application/json" curl -X POST -d @kairos_query.txt http://<kairos-ip>:8080/api/v1/datapoints/query --header "Content-Type:application/json"<file_sep>/collectd/Dockerfile FROM stakater/base:latest MAINTAINER <NAME> <<EMAIL>> RUN apt-get update && \ apt-get install collectd --no-install-recommends -y RUN wget -O /usr/lib/collectd/kairosdb_writer.py \ https://raw.githubusercontent.com/kairosdb/collectd-kairosdb/master/kairosdb_writer.py ADD collectd.conf /etc/collectd/collectd.conf RUN service collectd stop RUN rm -f /etc/init/collectd.conf RUN rm -f /etc/init.d/collectd ADD run.sh /usr/local/sbin/run_collectd.sh ENTRYPOINT ["/usr/local/sbin/run_collectd.sh"]<file_sep>/README.md # docker-images Docker Images ### Commands 1. The printenv command prints the names and values of all currently defined environment variables: printenv 2. To examine the value of a particular variable, we can specify its name to the printenv command: printenv TERM e.g. printenv JAVA_HOME 3. Open a command-line terminal type the following command to list total number of Ethernet devices on Linux: $ lspci $ lspci | less $ lspci | grep -i eth 4. To list actual ip address assigned to the interface, enter: $ ifconfig $ ifconfig eth0 5. run container and bash into it `docker run --name stakater_grails --rm -i -t stakater/grails:2.3.8 bash` This will create a container named stakater_grails and start a Bash session.<file_sep>/gocd-agent/16.11.0/Dockerfile FROM gocd/gocd-agent-deprecated:16.11.0 MAINTAINER Hazim <<EMAIL>> RUN apt-get -y update RUN apt-get -y install wget python-pip python-dev #Install Python -- Using latest because the rest install 3.4.2 RUN mkdir -p /etc/downloads/python RUN mkdir -p /opt/bin RUN rm /usr/bin/python3 RUN wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh -P /etc/downloads/python RUN chmod +x /etc/downloads/python/Miniconda3-latest-Linux-x86_64.sh RUN /etc/downloads/python/Miniconda3-latest-Linux-x86_64.sh -bf -p /opt/python RUN ln -s /opt/python/bin/python /usr/bin/python3 RUN ln -s /opt/python/bin/pip /usr/bin/pip3 ENV PATH $PATH:/opt/bin RUN apt-get -y install jq uuid wget unzip RUN pip install --upgrade awscli #making lsb_release use python2, doesn't work with python3 at the moment RUN sed -i -e 's/python3/python/' /usr/bin/lsb_release RUN pip3 install --upgrade ruamel.yaml RUN apt-get clean # Install terraform RUN mkdir -p /opt/terraform RUN wget -nc -q https://releases.hashicorp.com/terraform/0.7.13/terraform_0.7.13_linux_amd64.zip -P /opt/terraform RUN unzip -q /opt/terraform/terraform_0.7.13_linux_amd64.zip -d /opt/terraform ENV PATH /opt/terraform:$PATH # base image's cmd CMD ["/sbin/my_init"] <file_sep>/tomcat/8/Dockerfile FROM stakater/java:oracle-8 MAINTAINER <NAME> <<EMAIL>> RUN apt-get update && \ apt-get install -yq --no-install-recommends wget pwgen ca-certificates && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* ENV TOMCAT_MAJOR_VERSION 8 ENV TOMCAT_MINOR_VERSION 8.0.11 ENV CATALINA_HOME /tomcat # INSTALL TOMCAT RUN wget -q https://archive.apache.org/dist/tomcat/tomcat-${TOMCAT_MAJOR_VERSION}/v${TOMCAT_MINOR_VERSION}/bin/apache-tomcat-${TOMCAT_MINOR_VERSION}.tar.gz && \ wget -qO- https://archive.apache.org/dist/tomcat/tomcat-${TOMCAT_MAJOR_VERSION}/v${TOMCAT_MINOR_VERSION}/bin/apache-tomcat-${TOMCAT_MINOR_VERSION}.tar.gz.md5 | md5sum -c - && \ tar zxf apache-tomcat-*.tar.gz && \ rm apache-tomcat-*.tar.gz && \ mv apache-tomcat* tomcat ADD create_tomcat_admin_user.sh /create_tomcat_admin_user.sh RUN mkdir /etc/service/tomcat ADD run.sh /etc/service/tomcat/run RUN chmod +x /*.sh RUN chmod +x /etc/service/tomcat/run EXPOSE 8080 # Use baseimage-docker's init system. CMD ["/sbin/my_init"] <file_sep>/nginx/with-consul-template/build.sh #!/bin/bash _consul_template_version=$1 _nginx_with_consul_template_tag=$2 _release_build=false if [ -z "${_consul_template_version}" ]; then source CONSUL_TEMPLATE_VERSION _consul_template_version=$CONSUL_TEMPLATE_VERSION _nginx_with_consul_template_tag=$CONSUL_TEMPLATE_VERSION _release_build=true fi echo "CONSUL_TEMPLATE_VERSION: ${_consul_template_version}" echo "DOCKER TAG: ${_nginx_with_consul_template_tag}" echo "RELEASE BUILD: ${_release_build}" docker build --build-arg CONSUL_TEMPLATE_VERSION=${_consul_template_version} --tag "stakater/nginx-with-consul-template:${_nginx_with_consul_template_tag}" --no-cache=true . if [ $_release_build == true ]; then docker build --build-arg CONSUL_TEMPLATE_VERSION=${_consul_template_version} --tag "stakater/nginx-with-consul-template:latest" --no-cache=true . fi <file_sep>/filebeat/README.md ## filebeat docker image based on Ubuntu 14.04 Run the latest container with: `docker run stakater/filebeat` ## Advanced Build an image: `docker build -t stakater/filebeat .` Push an image: `sudo docker push stakater/filebeat` _Note_ you might have to login first before you can push the image to docker-hub `sudo docker login` Before starting Filebeat, you should look at the configuration options in the configuration file, for example /etc/filebeat/filebeat.yml Tell filebeat container three things: 1. location (directory) containing logs to beat 2. logstash server host 3. logstash server port e.g. `docker run -d -v "/Users/rasheed/Documents/projects/pliro/ams/logs:/var/log/app" -e "LOGSTASH_HOST=192.168.99.100" -e "LOGSTASH_PORT=5044" stakater/filebeat` /etc/init.d/filebeat start ./filebeat -e -d "*" -c filebeat.yml run filebeat with full debug logs... ./filebeat -e -d "*" -c /etc/filebeat/filebeat.yml Run filebeat manually with debug level logs: /usr/bin/filebeat -e -d "*" -c /etc/filebeat/filebeat.yml CMD ["/usr/bin/filebeat", "-e", "-d", "\"*\"", "-c", "/etc/filebeat/filebeat.yml"] filebeat logs can be found at: /var/log/mybeat/mybeat and level can be changed in filebeat.yml filebeat & elasticsearch Before starting Filebeat for the first time, run this command (replace ELASTIC_SEARCH_HOST with the appropriate hostname) to load the default index template in Elasticsearch: curl -XPUT 'http://{ELASTIC_SEARCH_HOST}:9200/_template/filebeat?pretty' -d@/{PATH_TO_THIS_FILE}/filebeat.template.json And the response should be: { "acknowledged" : true } Things to do: 1. push the filebeat container to dockehub<file_sep>/collectd/README.md # Collectd Dockerfile based on Ubuntu 16.04 Run the latest container with: `docker run stakater/collectd` ## Advanced Build an image: `docker build -t stakater/java:collectd .` Push an image: `sudo docker push stakater/java:collectd` _Note_ you might have to login first before you can push the image to docker-hub `sudo docker login` ## ToDo's 1. templatize collectd.conf - assume you have multiple servers to write to!<file_sep>/filebeat/docker-entrypoint.sh #!/bin/sh set -e # Render config file cat /etc/filebeat/filebeat.yml | sed "s/LOGSTASH_HOST/$LOGSTASH_HOST/" | sed "s/LOGSTASH_PORT/$LOGSTASH_PORT/" > /etc/filebeat/filebeat.yml.tmp cat /etc/filebeat/filebeat.yml.tmp > /etc/filebeat/filebeat.yml rm /etc/filebeat/filebeat.yml.tmp exec "$@"<file_sep>/kairosdb/Dockerfile # Dockerfile to run KairosDB on Cassandra. Configuration is done through environment variables. # # The following environment variables can be set # # $CASS_HOSTS [kairosdb.datastore.cassandra.host_list] (default: localhost:9160) # Cassandra seed nodes (host:port,host:port) # # $REPFACTOR [kairosdb.datastore.cassandra.replication_factor] (default: 1) # Desired replication factor in Cassandra # # $PORT_TELNET [kairosdb.telnetserver.port] (default: 4242) # Port to bind for telnet server # # $PORT_HTTP [kairosdb.jetty.port] (default: 8080) # Port to bind for http server # # Sample Usage: # docker run -P -e "CASS_HOSTS=192.168.1.63:9160" -e "REPFACTOR=1" stakater/kairosdb FROM stakater/java:oracle-8 MAINTAINER <NAME> <<EMAIL>> ARG KAIROSDB_VERSION # install gettext for envsubst RUN apt-get update RUN apt-get install -y gettext-base # Install KAIROSDB RUN wget -O /var/cache/kairosdb_${KAIROSDB_VERSION}-1_all.deb \ https://github.com/kairosdb/kairosdb/releases/download/v${KAIROSDB_VERSION}/kairosdb_${KAIROSDB_VERSION}-1_all.deb RUN dpkg -i /var/cache/kairosdb_${KAIROSDB_VERSION}-1_all.deb ADD kairosdb.properties /tmp/kairosdb.properties ADD runKairos.sh /usr/local/sbin/run_kairosdb.sh ADD logback.xml /opt/kairosdb/conf/logging/logback.xml ENTRYPOINT ["/usr/local/sbin/run_kairosdb.sh"]<file_sep>/terraform/README.md # What is terraform Terraform provides a common configuration to launch infrastructure — from physical and virtual servers to email and DNS providers. Once launched, Terraform safely and efficiently changes infrastructure as the configuration is evolved. Simple file based configuration gives you a single view of your entire infrastructure. [Terraform](https://www.terraform.io/) # Phusion Docker Image with `terraform` & `make` installed This is a phusion based docker image which has `terraform 0.6.12`, `make` `awscli` and `s3cmd` installed. It's purpose is to run any terraform based project that is placed in the container. You can enter any command required to build your project other than the `terraform` commands as well (e.g. make etc.) ## Usage ### Creating a Container: ``` docker run -d --name stakater_terraform -v /etc/myTerraformCode:/usr/src/app ``` Map the directory which contains your terraform code to `/usr/src/app`. ### Running Your Code: To run your code, pass commands to the docker container using `exec` ``` docker exec stakater_terraform /bin/bash -c "<command here>" ``` e.g. ``` docker exec stakater_terraform /bin/bash -c "terraform apply" ``` OR ``` docker exec stakater_terraform /bin/bash -c "make myApp" ``` <file_sep>/gradle/Dockerfile FROM stakater/java:oracle-8 MAINTAINER <NAME> <<EMAIL>> # Use baseimage-docker's init system. CMD ["/sbin/my_init"] # make sure the package repository is up to date RUN echo "deb http://archive.ubuntu.com/ubuntu trusty main universe" > /etc/apt/sources.list RUN apt-get -y update # install gradle RUN add-apt-repository ppa:cwchien/gradle RUN apt-get update RUN apt-get -y install gradle<file_sep>/nodejs/README.md ## node docker images based on Ubuntu 14.04 Run the latest container with: `docker run stakater/nodejs:only` ## Advanced Build an image: `docker build -t stakater/nodejs:only .` Push an image: `sudo docker push stakater/nodejs:only` _Note_ you might have to login first before you can push the image to docker-hub `sudo docker login` ## includes * Ubuntu 14.04 LTS * nodejs 4.x * npm * gulp * grunt * yo * bower<file_sep>/gocd-agent/16.5.0-3305/Dockerfile FROM gocd/gocd-agent:16.5.0-3305 MAINTAINER Hazim <<EMAIL>> RUN apt-get -y update RUN apt-get -y install jq python-pip uuid wget unzip RUN pip install --upgrade awscli RUN apt-get clean # Install terraform RUN mkdir -p /opt/terraform RUN wget -nc -q https://releases.hashicorp.com/terraform/0.7.13/terraform_0.7.13_linux_amd64.zip -P /opt/terraform RUN unzip -q /opt/terraform/terraform_0.7.13_linux_amd64.zip -d /opt/terraform ENV PATH /opt/terraform:$PATH # base image's cmd CMD ["/sbin/my_init"] <file_sep>/nginx-prerender/README.md #Nginx with Prerender This docker images is a combination of nginx (official) & stakater/prerender, Inorder to run prerenderer and application in a single container<file_sep>/java/oracle/README.md ## Base image installed with Oracle Java stakater/java:oracle-8 Oracle Java 8 stakater/java:oracle-7 Oracle Java 7 stakater/java:oracle-6 Oracle Java 6<file_sep>/tomcat/README.md ## tomcat docker images<file_sep>/mysql-backup-restore-s3/README.md Based on Ubuntu 16.04 LTS Xenial The image offers following features: 1. backup of mysql database 2. upload of mysql backup to s3 3. download mysql backup from s3 4. restore s3 backup Build an image: If you are using local Docker, following command will build a local image, skip this setup if you want to get the latest image from the docker hub. `docker build -t stakater/mysql-backup-restore-s3 .` Run the latest container with: `docker run stakater/mysql-backup-restore-s3` If the image isn't found locally it will automatically pull from the docker hub. Run and link the container with the mysql container from where it will clone the backup and upload to S3: `docker run -d --link mysqlbackuprestores3_mysql_1:mysql -v $PWD:/backup -e CRON_TIME="*/2 * * * *" -e MYSQL_USER=root -e MYSQL_PASS=<PASSWORD> -e S3_BUCKET_NAME=you_bucket_unique_name -e AWS_ACCESS_KEY_ID=your_access_id -e AWS_SECRET_ACCESS_KEY="your_secret_key" -e AWS_DEFAULT_REGION=your_bucket_region -e LAST_BACKUP=20160824.sql stakater/mysql-backup-restore-s3` You can override the already set environment variable by passing them as parameter shown above. You can get AWS_ID and AWS_SECRET_ACCESS_KEY from your developer aws console. Your bucket name should be unique universally. The LAST_BACKUP is set if you want to a specific restore point, else remove this and it will automatically fetch and restore the last uploaded backup. If you dont want to restore backup set "-e RESTORE=false" in above command as it is set TRUE by default. Push an image if you changed anything locally: `sudo docker push stakater/mysql-backup-restore-s3` <file_sep>/nginx/with-consul-template/README.md docker-nginx-consul-template ============================ A Consul Template powered Nginx docker container. `docker run stakater/stakater/nginx-with-consul-template:latest`
4059a2367491621139d241a15e1d16c5c7ccc3e9
[ "Markdown", "Dockerfile", "Shell" ]
42
Markdown
bobweston/docker-images
c4b474b262449dc8d5047a693a7f2127d16737c5
d4c11f67f1f595e9d930c424bec53fcedbf0d205
refs/heads/master
<file_sep>package Parcial; import java.util.Scanner; public class Pregunta5 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner lector = new Scanner(System.in); System.out.print("Introduzca una cadena de texto : "); String sPalabra=lector.nextLine(); int inc = 0; int des = sPalabra.length()-1; boolean bError = false; while ((inc<des) && (!bError)){ if (sPalabra.charAt(inc)==sPalabra.charAt(des)){ inc++; des--; } else { bError = true; } } if (!bError) System.out.println(sPalabra + " es un PALINDROMO"); else System.out.println(sPalabra + " no es un palindromo"); } }
05acc4fe8e67ee1b6927f14667c3002188f3f8eb
[ "Java" ]
1
Java
FrankGx01/ParcialPOO
76fb6025662835b6b2e1ddf774e67e8ef7f40817
fe5af958447e2774e382d44b77da0e64dfec15a2
refs/heads/master
<file_sep>let loadSettings = async () => { window.settings = await $.ajax(`pages/settings.json`) // Work with settings $("title").text(settings.title) if (settings.favicon) setFavicon(settings.favicon) for (icon of settings.sidebar_icons.split(" ")) { let elem = document.createElement("i") $(elem).addClass("mdi").addClass("mdi-" + icon) $("sidebar .ico").append(elem).append(" ") } $("include").attr("sect", settings.default_sect) if (!settings.top_color || !settings.bottom_color) throw Error("No colors defined in settings.json") startColor = one.color(settings.top_color) endColor = one.color(settings.bottom_color) } let loadIncludes = async () => { while ($("include").length) await (async () => { let elem = $("include").first() let sect = elem.attr("sect") if (!sect) throw Error("No sect specified for include statement") let page = await $.ajax(`pages/${sect}.html`) if (!page.includes("Error response")) { elem.replaceWith($.parseHTML(page, document, true)); } else throw Error(`Sect \'${sect}\' does not exist.`) })() } let loadSmoothScroll = () => $('a[href^="#"]').on("click", evt => { evt.preventDefault(); let elem = $($.attr(evt.target, "href")) if (elem.children("sect").length != 0) elem.click(); else { $('html, body').animate({ scrollTop: elem.offset().top }, 500, "easeInOutQuart"); } }) let animateStartup = () => { { // Preps the sidebar for the anim sidebar = $("sidebar") sidebar.css("transition-duration", "0") hideSidebar(/* slow unhide */ true) sidebar.css({"transition-duration": "", "left": ""}) } $("sect").not("sect sect").each((index, item) => { let elem = $(item); if (elem.parent()[0].tagName.toLowerCase() == "sect") return; elem.animate({ opacity: 1, top: 0 }, 700 + (200 * index), "easeInOutQuart") }) showSidebar() } <file_sep>/////////////////////////////////////////////////////////////////////////////// let startColor = one.color("#fff") let endColor = one.color("#000") function colorGen(forceReplace = false) { let numSects = $("sect").not("sect sect").length - 2; colorForSect = (pos) => { // Emulating design from: https://git.io/vNA8b calc = (prop) => { let start = startColor[prop](); let end = endColor[prop](); let weight = pos / numSects; return start * (1 - weight) + end * weight }; return new one.color.RGB(calc("red"), calc("green"), calc("blue")).hex() } $("sect").not("sect sect").each((index, item) => { if (index == 0 || index == (numSects + 1)) return; if (!$(item).attr("background") || forceReplace) $(item).attr("background", colorForSect(index - 1).toUpperCase()) }) } /////////////////////////////////////////////////////////////////////////////// async function debug() { // Enables debug functions let debugScript = document.createElement("script") $(debugScript).attr("src", "backend/js/debug.js") $("deps").append(debugScript) $("#onpage-title")[0].innerText += " [DEBUG]" window.debug = null; } function getNearestAttr(elem, attr) { // Loops through the hierarchy until it finds an element with attr set elem = $(elem) result = elem.attr(attr) while (!result && (elem.prop("tagName") != undefined)) { elem = elem.parent() result = elem.attr(attr) } return result } function getNearestBackground(elem) { return getNearestAttr(elem, "background") } function setFavicon(url) { $("link[rel*='icon']").prop("href", url) } //https://css-tricks.com/snippets/javascript/lighten-darken-color/ function adjustColor1(col, amt) { var usePound = false; if (col[0] == "#") { col = col.slice(1); usePound = true; } var num = parseInt(col,16); var r = (num >> 16) + amt; if (r > 255) r = 255; else if (r < 0) r = 0; var b = ((num >> 8) & 0x00FF) + amt; if (b > 255) b = 255; else if (b < 0) b = 0; var g = (num & 0x0000FF) + amt; if (g > 255) g = 255; else if (g < 0) g = 0; return (usePound?"#":"") + (g | (b << 8) | (r << 16)).toString(16); } //https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript function genID() { function s4() { return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); } // Adapted from https://stackoverflow.com/a/36888120 function isLight(col) { if (col[0] == "#") col = col.slice(1); if (col == "fff") col = "ffffff" let num = parseInt(col, 16) var r = (num >> 16) var g = ((num >> 8) & 0x00FF) var b = (num & 0x0000FF) // calculate "perceptive luminance" // NOTE: human eye favors green let luma = ((0.299 * r) + (0.587 * g) + (0.114 * b)) / 255; return luma > 0.5 } function darkRipple(_, ripple) { ripple.css("backgroundColor", "rgba(0,0,0,0.26)") } function hideSidebar(slowly) { let sidebar = $("sidebar") sidebar.addClass("hidden") if (sidebar.width() == 180) sidebar.addClass("cssLacksAMaxFunction") if (slowly) sidebar.addClass("slowUnhide") } function showSidebar() { let sidebar = $("sidebar") sidebar.removeClass("hidden").removeClass("cssLacksAMaxFunction") setTimeout(() => sidebar.removeClass("slowUnhide"), 1000) } function findSect(event) { item = $(event.target) while (item.parent()[0].tagName.toLowerCase() == "sect" && $(item.parent()[0]).attr("id") == undefined) item = item.parent() if (item.attr("id") == undefined) item = item.parent() return item } <file_sep>$(() => (async () => { /////////////////////////////////////////// // Error handling // NOTE: Always keep this up at the top, otherwise it might miss errors /////////////////////////////////////////// window.onerror = (message) => { alert("Something has gone wrong on this page. Reloading...\n\n" + message) location.reload() } /////////////////////////////////////////// // Compensate for TinyURL adding on #featured (it just bothers me) /////////////////////////////////////////// window.location = "#" /////////////////////////////////////////// // Loading /////////////////////////////////////////// await loadSettings() await loadIncludes() // NOTE: Make sure this happens before sect handling colorGen() // Generates the background attribute for each section await sectSetup() // Configures the section loadSmoothScroll() // Enable smooth scrolling animateStartup() // NOTE: Always keep last /////////////////////////////////////////// // Extras /////////////////////////////////////////// try { if (settings.beta) $("#onpage-title")[0].innerText += " (Beta)" if (settings.debug) debug() } catch (e) {} $(document).on("keyup", handleEscape) $("sidebar").children(".ico").ripple() })()) <file_sep>async function sectSetup(reload = false) { for (sect of $("sect")) await processSect($(sect), reload) } async function processSect(item, reload = false) { let elem = $(item); let props = await sect_attrs(elem, reload); // Parse the sections properties let colors = await sect_color(elem, props.isSub); if (!props.isSub && !reload) await sect_animations(elem, colors.f); if (props.simple) return; if (props.isSub) await sect_expanding(elem, colors.b); if (!props.isSub) await sect_navi(elem, colors.b, colors.f); } async function sect_attrs(elem, reload = false) { // Specify the href attribute on any sect to make it a link let href = elem.attr("href") if (href && !reload) elem.click(() => window.location = href) // Specify the icon attribute on any sect to embed an icon into it let icon = elem.attr("icon") if (icon && !(elem.children("sect").length) && !reload) { let icn = $(document.createElement("icn")) icn.addClass("mdi") icn.addClass("mdi-" + icon) elem.prepend(icn) } let img = elem.attr("img") if (img && !reload) { // TODO } // Generate a random ID for sections lacking it let id = elem.attr("id"); if (!id && !reload) elem.attr("id", genID()) return { href: href, icon: icon, img: img, simple: elem.attr("no-nav") != undefined, id: id, isSub: (elem.parent().prop("tagName") == "SECT") } } async function sect_color(elem, isSub) { // Fetch colors let background = getNearestBackground(elem) || "#ffffff"; let forceDark = false//getNearestAttr(elem, "force-dark-text") != undefined let forceLight = false//getNearestAttr(elem, "force-light-text") != undefined let foreground = (isLight(background) || forceDark) && !forceLight ? "#000" : "#fff"; if (isSub) background = "transparent"// TODO // Set background and text colors elem.css({ backgroundColor: background, color: foreground }); elem.find("*").css("color", foreground); // TODO: Buttons, links, etc return {b: background, f: foreground}; } async function sect_animations(elem, foreground) { let obj = { adaptPos: false } if (!isLight(foreground)) obj.callback = darkRipple elem.ripple(obj) elem.css({ opacity: 0, top: "200px" }) } async function sect_expanding(elem, background) { elem.hide() sect = elem.parent() if (sect.data("expanding-handled")) return; let icn; icn = $(document.createElement("icn")) //icn.text(sect.attr("icon") ? sect.attr("icon") : "fullscreen") //icn.addClass("material-icons") icn.addClass("mdi") icn.addClass("mdi-" + (sect.attr("icon") ? sect.attr("icon") : "fullscreen")) sect.prepend(icn) let sectClick = e => { let item = findSect(e) item.off("click") setTimeout(() => item.children("icn").click(icnClick), 100) fillScreen(item.attr("id")) } let icnClick = e => { let item = findSect(e) item.children("icn").off("click") setTimeout(() => item.click(sectClick), 100) unfillScreen(item.attr("id")) } sect.click(sectClick) sect.data("expanding-handled", true) elem.data("expand-background", background) return } async function sect_navi(elem, background, foreground) { let navItem = document.createElement("li") let a = document.createElement("a") navItem.append(a) a.innerText = elem.find("h1")[0].innerText $(a).attr("href", `#${elem.attr("id")}`) // TODO: Fix the hover $(a).hover(function(event) { $(this).css({ backgroundColor: background, color: foreground }) }, function(event) { $(this).css({ backgroundColor: "transparent", color: "white" }); }) //$(a).click(() => false) // TODO: disable in css once rippleOnHover works //$(a).css("backgroundColor", "black") //$(a).css("color", "white") $(a).ripple({ rippleOnHover: true, callback: (_, ripple) => { //TODO: Activate once rippleOnHover works //ripple.css("backgroundColor", background) } }) $("#nav").append(navItem) } <file_sep>console.log("DEBUG TOOLS ENABLED") // Set the overall color scheme of the page async function testColorScheme(color1, color2) { // Overwrite color defenitions startColor = one.color(color1) endColor = one.color(color2) colorGen(true) // This will forcibly replace the old colors $("#nav").empty() // Remove the navigation elements await sectSetup(true) // Rerun the sections through generation loadSmoothScroll() // Fix smooth scrolling } function testError() { setTimeout(() => {throw Error("This is a test")}, 200) } <file_sep>function fillScreen(id) { item = $(id.startsWith("#") ? id : "#" + id) parentExpanded = item.parent().hasClass("fill") // Icon management icn = item.children("icn") fadeText(icn, "close") item.css("height", item.height()) item.children("sect").fadeIn(600, "easeInOutQuart") item.data("initial-offset", $(window).scrollTop()) // Store the initial scroll state if (!parentExpanded) hideSidebar() // Hide navigation if (parentExpanded) { item.parent().css("minHeight", "200vh") // adjustColor(item.parent().data("expand-background"), -50) } item.addClass("fill") $('html').css("overflow", "hidden") $('html, body').animate({ scrollTop: item.offset().top }, 500, "easeInOutQuart") // Move the element up // Adjust children item.children("h1").addClass("root") // Make h1 larger item.children("icn").addClass("close") // Make the expand button into a close button item.children("p").slideUp(500, "easeInOutQuart") // Hide the collapsed state description pushEsc(id) } function unfillScreen(id) { item = $(id.startsWith("#") ? id : "#" + id) parentExpanded = item.parent().hasClass("fill") // Icon management icn = item.children("icn") fadeText(icn, item.attr("icon") ? item.attr("icon") : "fullscreen") item.children("sect").fadeOut(500, "easeInOutQuart") // Return children to default state item.children("h1").removeClass("root") // Make h1 the normal size item.children("icn").removeClass("close") // Move the close button into an expand button item.children("p").slideDown(500, "easeInOutQuart") // Show collapsed state description //$("html, body").scrollTop(item.offset().top)\ //setTimeout(() => $("body").css("overflow", ""), 500) // Restore item size if (!parentExpanded) $('html').css("overflow", "") item.removeClass("fill") item.animate({scrollTop: 0}, 500, "easeInOutQuart") $('html, body').animate({ scrollTop: item.data("initial-offset") }, 500, "easeInOutQuart") if (!parentExpanded) showSidebar() // Show navigation // Finish up setTimeout(() => { item.css("height", "") if (parentExpanded) { item.parent().css({ minHeight: "", //backgroundColor: adjustColor(item.parent().data("expand-background"), 10) }) } }, 510) popEsc() } function fadeText(elem, text) { elem.animate({opacity: 0}, 100, "easeInOutQuart", () => { elem.alterClass("mdi-*", "mdi-" + text) elem.animate({opacity: 1}, 100, "easeInOutQuart") }) } /////////////////////////////////////////// // Escape key handling /////////////////////////////////////////// let escapeStack = []; let stackPopped = false; function handleEscape(e) { e = e || window.event; if (e.keyCode == 27 && escapeStack.length) { stackPopped = true; $("#" + escapeStack.pop()).children("icn").click() } } function pushEsc(id) { escapeStack.push(id) } function popEsc() { if (!stackPopped) { escapeStack.pop() } stackPopped = false; }
dec13878abe5ac9f57c19fa1ac0072851c399ce3
[ "JavaScript" ]
6
JavaScript
AdrianVovk/WebsiteBackend
3e3619e72e7254d091173aa3351977b4a0aacb44
74e08427fd53fe0989fbfceeab9fb6a5e25f1e41
refs/heads/master
<repo_name>yacine21/tumor-heatmap<file_sep>/main.py import seaborn as sbn import matplotlib.pyplot as plt import openpyxl as xcell import numpy as np def get_max_amplitude(filename): workbook = xcell.load_workbook('signals/{}'.format(filename)) sheet = workbook.active amplitudes = [] for i in range(2,sheet.max_row): amplitudes.append(sheet['B'][i].value) return max(amplitudes) def create_matrix(): full_map = np.zeros((150,150)) return full_map position_0_0 = get_max_amplitude('SIGNAL FOR X=0 Y=0.xlsx') position_0_150 = get_max_amplitude('SIGNAL FOR X=0 Y=150.xlsx') position_6_29 = get_max_amplitude('SIGNAL FOR X=6 Y=29.xlsx') position_20_121 = get_max_amplitude('SIGNAL FOR X=20 Y=121.xlsx') position_24_117 = get_max_amplitude('SIGNAL FOR X=24 Y=117.xlsx') position_24_121 = get_max_amplitude('SIGNAL FOR X=24 Y=121.xlsx') position_24_125 = get_max_amplitude('SIGNAL FOR X=24 Y=125.xlsx') position_28_121 = get_max_amplitude('SIGNAL FOR X=28 Y=121.xlsx') position_75_76 = get_max_amplitude('SIGNAL FOR X=75 Y=76.5.xlsx') position_126_29 = get_max_amplitude('SIGNAL FOR X=126 Y=29.xlsx') position_126_121 = get_max_amplitude('SIGNAL FOR X=126 Y=121.xlsx') position_150_0 = get_max_amplitude('SIGNAL FOR X=150 Y=0.xlsx') position_150_150 = get_max_amplitude('SIGNAL FOR X=150 Y=150.xlsx') tumor_heatmap = create_matrix() tumor_heatmap[0][0] = position_0_0 print('max amplitude at 0x0 : {}'.format(position_0_0)) tumor_heatmap[0][149] = position_0_150 tumor_heatmap[6][29] = position_6_29 tumor_heatmap[20][121] = position_20_121 tumor_heatmap[24][117] = position_24_117 tumor_heatmap[24][121] = position_24_121 tumor_heatmap[24][125] = position_24_125 tumor_heatmap[28][121] = position_28_121 tumor_heatmap[75][76] = position_75_76 tumor_heatmap[126][29] = position_126_29 tumor_heatmap[126][121] = position_126_121 tumor_heatmap[149][0] = position_150_0 tumor_heatmap[149][149] = position_150_150 plot = sbn.heatmap(tumor_heatmap, cmap="Blues") plt.show()
837e1bc20b3e820cb902b12f0190335561565d15
[ "Python" ]
1
Python
yacine21/tumor-heatmap
c7ad9af3b7534cbc36fcb714f0fe0889009ef96e
c1a6ae474737712061902a02b2803deedd3008c6
refs/heads/master
<file_sep>const fs = require('fs-extra'); const ip = require('ip'); const isWin = process.platform === 'win32'; const EOL = isWin ? '\r\n' : '\n'; const HOSTS = isWin ? 'C:/Windows/System32/drivers/etc/hosts' : '/etc/hosts'; const readLine = line => { const enabled = !line.startsWith('#'); if (!enabled) { line = line.substr(1); } const lineSplit = line.split(/\s+/); if (!lineSplit[0] || (!ip.isV4Format(lineSplit[0]) && !ip.isV6Format(lineSplit[0]))) { return null; } return { enabled, ip: lineSplit[0], others: lineSplit.slice(1).join(' '), }; }; const printLine = obj => { return `${obj.enabled ? '' : '#'}${obj.ip} ${obj.others}${EOL}`; } const isGroupEnd = line => { return line === '#===='; }; const isGroupStart = line => { if (!isGroupEnd(line) && line.startsWith('#====')) { return line.substr(5).trim(); } return false; }; exports.readHosts = () => { let group = 'common'; const hostsObj = {}; const hosts = fs.readFileSync(HOSTS, 'utf-8'); const splits = hosts.split(EOL); splits.forEach(line => { line = line.trim(); if (!line) return; const _g = isGroupStart(line); if (_g) { group = _g; } else if (isGroupEnd(line)) { group = 'common'; } else { const host = readLine(line); if (host) { hostsObj[group] = hostsObj[group] || []; hostsObj[group].push(host); } } }); return hostsObj; } exports.print = hostsObj => { let output = ''; for(let [group, hosts] of Object.entries(hostsObj)) { if (group === 'common') { hosts.forEach(host => { output += printLine(host); }); } else { output += `#==== ${group}${EOL}`; hosts.forEach(host => { output += printLine(host); }); output += `#====${EOL}`; } output += EOL; } fs.writeFileSync(HOSTS, output, 'utf-8'); } exports.isGroupEnabled = (hostsObj, group) => { const hosts = hostsObj[group]; return hosts.every(host => host.enabled); } exports.toggleGroup = (hostsObj, group, enabled) => { const hosts = hostsObj[group]; hosts.forEach(host => { host.enabled = enabled; }); }<file_sep># xhost [![NPM version][npm-image]][npm-url] [![npm download][download-image]][download-url] [npm-image]: https://img.shields.io/npm/v/xhost.svg?style=flat-square [npm-url]: https://npmjs.org/package/xhost [download-image]: https://img.shields.io/npm/dm/xhost.svg?style=flat-square [download-url]: https://npmjs.org/package/xhost [HostAdmin](https://addons.mozilla.org/en-US/firefox/addon/hostadmin/) implementation in Node CLI *Tips: ONLY test on Node v8+* ## Usage - [Fix permissions](https://code.google.com/archive/p/fire-hostadmin/wikis/GAIN_HOSTS_WRITE_PERM.wiki) - Edit `hosts` based on [Group syntax](#group-syntax) - `npm i -g xhost` - `xhost` ## Screenshot ![](https://cdn.int64ago.org/m4vq42fj.gif) ## Group syntax ```bash #==== GROUPNAME [...] #==== ``` for example: ```bash #==== Project 1 #127.0.0.1 localhost1 127.0.0.1 localhost2 127.0.0.1 localhost3 #==== #==== Project 2 #127.0.0.1 localhost1 #127.0.0.1 localhost2 #127.0.0.1 localhost3 #==== ``` ## License MIT<file_sep>#!/usr/bin/env node const main = require('./src/index'); const updateNotifier = require('update-notifier'); const pkg = require('./package'); updateNotifier({ pkg }).notify(); const args = process.argv.slice(2); if (args[0] && args[0] === '-v' || args[0] === '--version') { console.log(pkg.version); process.exit(); } main();
d8bbeec609a7cecebe8c6535ac290eb78f81d29c
[ "JavaScript", "Markdown" ]
3
JavaScript
int64ago/xhost
12b09a1860f91211c6c15ec7a51751a916e74186
a747489cca4c7bfc502ae8b662c9eeb04248586d
refs/heads/master
<file_sep>var express = require('express'); var www = require('./src/www.js'); var server = require('./src/server.js'); var app = express(); global.__dirname = __dirname; global.__path = __dirname; app.get('/', www('pages/index.html')); app.get('/css/:file', www('styles/')); app.get('/js/:file', www('scripts/')); var http = app.listen(8090); var socket = server(http); console.log('Servidor iniciado!');<file_sep>var System = function(view, input) { var newRow = $('<div class="row"></div>'); var socket = io.connect(); var logged = false; this.submit = function(event) { event.preventDefault(); var value = input.val(); if(value != "") { input.val(""); if(isCommand(value)) { command(value); } else if(logged) { socket.emit('sendMessage', { message: value, direct: false, destination: "" }, function(data) { createRow('> [' + formatDate(data.date) + ']' + data.user + ": " + data.message, 'lime'); $(document).scrollTop(view.height()); }); } else { createRow('> ' + value); } } } var command = function(value) { var command = ""; value = value.substring(1); splitValue = value.split(" "); command = splitValue[0]; value = value.substring(splitValue[0].length + 1); switch(command) { case 'register': data = value.split(" "); if(data.length > 2) { } else if(data.length < 2) { } else { registerCommand(data[0], data[1]); } break; case 'login': data = value.split(" "); if(data.length > 2) { } else if(data.length < 2) { } else { loginCommand(data[0], data[1]); } break; case 'clear': view.html(""); break; } } var registerCommand = function(username, password) { socket.emit('register', { username: username, password: <PASSWORD> }, function(confirmed) { if(confirmed) { logged = true; createRow('> Registrado com sucesso'); createRow('> Seja bem vindo(a) ' + username); createRow('>'); socket.on('updateMessages', function(data) { createRow('> [' + formatDate(data.date) + ']' + data.user + ": " + data.message); $(document).scrollTop(view.height()); }); } }); } var loginCommand = function(username, password) { socket.emit('login', { username: username, password: <PASSWORD> }, function(exist, confirmed) { if(exist && confirmed) { logged = true; createRow('> Seja bem vindo(a) ' + username); createRow('>'); socket.on('updateMessages', function(data) { createRow('> [' + formatDate(data.date) + ']' + data.user + ": " + data.message); $(document).scrollTop(view.height()); }); } }); } var formatDate = function(timestamp) { var date = new Date(timestamp); var day = date.getDate(); day = day < 10 ? "0" + day : day; var month = 1 + date.getMonth(); month = month < 10 ? "0" + month : month; var year = date.getFullYear(); var hour = date.getHours(); hour = hour < 10 ? "0" + hour : hour; var minute = date.getMinutes(); minute = minute < 10 ? "0" + minute : minute; var second = date.getSeconds(); second = second < 10 ? "0" + second : second; return day + '/' + month + '/' + year + ' ' + hour + ':' + minute + ':' + second; } var createRow = function(message, color = 'white') { var row = newRow.clone(); row.text(message); row.css('color', color); view.append(row); } var isCommand = function(value) { if(value[0] == "/") { return true; } return false; } }
ea9678806cf8854846aedc56745fcdce05071378
[ "JavaScript" ]
2
JavaScript
RRC97/node.js-console-chat
0420f1905f88e9eee80fed2defb04aa729fefd0b
145dd8a1a9d2cd2bec0321091e1cbcd192c948cb
refs/heads/master
<repo_name>fernsehmuell/reaper_scripts<file_sep>/Mediacomposer_like_functions/fernsehmuell_MarkClip_(T).lua -- @version 1.0 -- @author <NAME> -- @changelog -- Initial release --emulate avid mediacomposer MARK CLIP functionality --if one or more tracks are selected only use these tracks --if no track is selected search for nearest cuts to cursor position in all tracks and set in/out function get_position() playstate=reaper.GetPlayState() --0 stop, 1 play, 2 pause, 4 rec possible to combine bits if playstate==1 or playstate==4 then return reaper.GetPlayPosition() else return reaper.GetCursorPosition() end end function get_last_timecode() -- get last timecode of whole project (is there an easier way???) last_tc=0 for t=1, reaper.GetNumTracks(),1 do Track= reaper.GetTrack(0,t-1) --get track if reaper.GetTrackNumMediaItems(Track)>0 then mediaitem=reaper.GetTrackMediaItem(Track, reaper.GetTrackNumMediaItems(Track)-1) -- get last item in_point=reaper.GetMediaItemInfo_Value(mediaitem, "D_POSITION") out_point=in_point + reaper.GetMediaItemInfo_Value(mediaitem, "D_LENGTH") if out_point>last_tc then last_tc=out_point end end end return last_tc end function get_closest_in_point_in_all_selected_tracks(pos,next) -- next=0 point has to be <=pos, next=1 point has to be <pos in_pos=0 track_in_pos=0 for t=1,number_of_tracks_to_scan,1 do for i=#timecodes[t],1,-1 do if next==0 then result=timecodes[t][i]<=pos else result = timecodes[t][i]<pos end if result then track_in_pos=timecodes[t][i] break end end if track_in_pos>in_pos then in_pos=track_in_pos end end return in_pos end function get_closest_out_point_in_all_selected_tracks(pos) --next=0 point has to be <=pos, next=1 point has to be <pos out_pos=last_timecode --get last timecode (project end) track_out_pos=out_pos for t=1,number_of_tracks_to_scan,1 do for i=1, #timecodes[t],1 do if timecodes[t][i]>pos then track_out_pos=timecodes[t][i] break end end if track_out_pos<out_pos then out_pos=track_out_pos end end return out_pos end function is_this_edit_in_all_selected_tracks(pos) found_in_tracks=0 for t=1,number_of_tracks_to_scan,1 do for i=1,#timecodes[t], 1 do if timecodes[t][i]==pos then found_in_tracks=found_in_tracks+1 break end end if t>found_in_tracks then return 0 end end return 1 end function clear_all_in_and_out_markers() retval, marker_count, regions_count = reaper.CountProjectMarkers(0) -- get number of markers for i=marker_count-1,0,-1 do -- count backwards, so numbering of markers does not change! index, isrgn, pos, rgnend, name, markrgnindex = reaper.EnumProjectMarkers2(0, i) -- get name of marker i if name == " [ in" or name == " out ]" then reaper.DeleteProjectMarkerByIndex(0, index-1) -- delete marker if it is a IN or OUT marker end end end function main() reaper.Undo_BeginBlock() timecodes={} -- array holding all edit timecodes [track][itemnumber] tracks_count=reaper.GetNumTracks() selected_tracks_count=reaper.CountSelectedTracks(0) if selected_tracks_count>0 then number_of_tracks_to_scan=selected_tracks_count else number_of_tracks_to_scan=tracks_count end last_timecode=get_last_timecode() playstate=reaper.GetPlayState() --0 stop, 1 play, 2 pause, 4 rec possible to combine bits if playstate==1 then reaper.Main_OnCommand(1008,0) reaper.Main_OnCommand(1016,0) end --stop as mediacomposer does (do we need that?) if playstate==1 or playstate==4 then position=reaper.GetPlayPosition() else position=reaper.GetCursorPosition() end --get cursor position --find in and out points for t=1,number_of_tracks_to_scan,1 do timecodes[t]={} if selected_tracks_count>0 then Track= reaper.GetSelectedTrack(0,t-1) --get a selected track else Track= reaper.GetTrack(0,t-1) --get track end items_count=reaper.GetTrackNumMediaItems(Track) --count items in track --analyse this track (collect all start and end points of all items) counter=0 for i=1,items_count,1 do counter=counter+1 mediaitem=reaper.GetTrackMediaItem(Track, i-1) out_point_last=out_point in_point=reaper.GetMediaItemInfo_Value(mediaitem, "D_POSITION") out_point=in_point + reaper.GetMediaItemInfo_Value(mediaitem, "D_LENGTH") if (i>1) and (in_point>out_point_last) then --check if there is a gap timecodes[t][counter]=out_point_last counter=counter+1 end timecodes[t][counter]=in_point end timecodes[t][counter+1]=out_point --set last edit point to list end if selected_tracks_count>0 then --normal operation: there are selected tracks --search the closest common IN Point to the cursor position in all tracks in_point=position first=0 while true do in_point=get_closest_in_point_in_all_selected_tracks(in_point,first) first=1 if is_this_edit_in_all_selected_tracks(in_point)==1 or in_point==0 then break end end --search the closest common OUT point to the cursor pos out_point=position while true do out_point=get_closest_out_point_in_all_selected_tracks(out_point) if is_this_edit_in_all_selected_tracks(out_point)==1 or out_point==last_timecode then if out_point<=in_point then out_point = last_timecode end break end end elseif tracks_count>0 then --no tracks selected, but there are tracks in_point=get_closest_in_point_in_all_selected_tracks(position,1) out_point=get_closest_out_point_in_all_selected_tracks(position) end --set new time selection retval, retval2 = reaper.GetSet_LoopTimeRange(1,0,in_point,out_point,0) clear_all_in_and_out_markers() --set new markers reaper.AddProjectMarker2(0, false, in_point, 0, " [ in", 0, 0xFFFF00|0x1000000) -- set marker reaper.AddProjectMarker2(0, false, out_point, 0, " out ]", 0, 0xFFFF00|0x1000000) -- set marker reaper.Undo_EndBlock("Mark Clip (fernsehmuell script)", -1) end -- main function end function start() if get_position()<=get_last_timecode() then main() end end reaper.defer(start) <file_sep>/Mediacomposer_like_functions/fernsehmuell_Step_forwards_40ms_(4).lua -- @version 1.0 -- @author <NAME> -- @changelog -- Initial release playstate=reaper.GetPlayState() --0 stop, 1 play, 2 pause, 4 rec possible to combine bits if playstate==0 or playstate==2 then reaper.MoveEditCursor(0.04, 0) end <file_sep>/Mediacomposer_like_functions/fernsehmuell_Clear_IN_Marks_(D).lua -- @version 1.0 -- @author <NAME> -- @changelog -- Initial release function main() reaper.Undo_BeginBlock() in_pos, out_pos = reaper.GetSet_LoopTimeRange(0,0,0,0,0) --get start and end point reaper.Main_OnCommand(40635,0) -- Time selection: Remove time selection (40635) reaper.SetProjExtState(0, "Fernsehmuell", "End_Point_before_Start_Point", out_pos) -- store outpoint in datastore reaper.SetProjExtState(0, "Fernsehmuell", "StartpointIsZero", "") -- clear IN-Point is Zero datastore Value retval, marker_count, regions_count = reaper.CountProjectMarkers(0) -- get number of markers for i=marker_count-1,0,-1 do -- count backwards, so numbering of markers does not change! index, isrgn, pos, rgnend, name, markrgnindex = reaper.EnumProjectMarkers2(0, i) -- get name of marker i if name == " [ in" then reaper.DeleteProjectMarkerByIndex(0, index-1) -- delete marker if it is an IN marker end end reaper.Undo_EndBlock("Clear IN marks (fernsehmuell script)", -1) end main() <file_sep>/Mediacomposer_like_functions/fernsehmuell_SetOUT_(O).lua -- @version 1.0 -- @author <NAME> -- @changelog -- Initial release function clear_all_out_markers() retval, marker_count, regions_count = reaper.CountProjectMarkers(0) -- get number of markers for i=marker_count-1,0,-1 do -- count backwards, so numbering of markers does not change! index, isrgn, pos, rgnend, name, markrgnindex = reaper.EnumProjectMarkers2(0, i) -- get name of marker i if name == " out ]" then reaper.DeleteProjectMarkerByIndex(0, index-1) -- delete marker if it is an OUT marker end end end function get_position() playstate=reaper.GetPlayState() --0 stop, 1 play, 2 pause, 4 rec possible to combine bits if playstate==1 or playstate==4 then return reaper.GetPlayPosition() else return reaper.GetCursorPosition() end end function main() reaper.Undo_BeginBlock() position=get_position() retval, value = reaper.GetProjExtState(0, "Fernsehmuell", "StartpointIsZero") -- check if IN point is set and =zero in_pos, out_pos = reaper.GetSet_LoopTimeRange(0,0,0,0,0) --get start and end point if ((in_pos>0) or (value=="True")) and in_pos<position then reaper.Main_OnCommand(40626,0) -- Time selection: Set end point (40626) reaper.SetProjExtState(0, "Fernsehmuell", "End_Point_before_Start_Point", "") -- clear datastore Value else -- out point is before IN Point or there is no IN-Point reaper.SetProjExtState(0, "Fernsehmuell", "End_Point_before_Start_Point", position) -- store outpoint in datastore retval, retval2 = reaper.GetSet_LoopTimeRange(1,0,in_pos,in_pos,0) -- clear OUT (set it to value of IN) end clear_all_out_markers() reaper.AddProjectMarker2(0, false, position, 0, " out ]", 0, 0xFFFF00|0x1000000) -- set marker reaper.Undo_EndBlock("Set OUT (fernsehmuell script)", -1) end main() <file_sep>/Mediacomposer_like_functions/fernsehmuell_Pause_(K).lua -- @version 1.0 -- @author <NAME> -- @changelog -- Initial release reaper.Main_OnCommand(1008,0) --pause reaper.Main_OnCommand(1016,0) --stop reaper.SetProjExtState(0, "Fernsehmuell", "Reverse_Play_Shuttle", 0) -- store state in datastore reaper.Main_OnCommand(40521, 0) -- set play speed to 1 <file_sep>/Mediacomposer_like_functions/fernsehmuell_Reverse_Play_Shuttle_(J).lua -- @version 1.1 -- @author <NAME> -- @changelog -- better way to get commandID of backgroundscript function is_playing_reverse() retval,value=reaper.GetProjExtState(0, "Fernsehmuell", "Reverse_Play_Shuttle") --check if reverse playing if not tonumber(value) then value="0" end if value=="1" then return 1 else return 0 end end function GetPath(str) if reaper.GetOS() == "Win32" or reaper.GetOS() == "Win64" then separator = "\\" else separator = "/" end return str:match("(.*"..separator..")") end function main() reaper.Undo_BeginBlock() is_new_value,filename,sectionID,cmdID,mode,resolution,val = reaper.get_action_context() reverse_function = reaper.AddRemoveReaScript(true, 0, GetPath(filename).."fernsehmuell_Reverse_Play_Shuttle_Background.lua", true) --reverse_function=reaper.NamedCommandLookup("_RS28389260f2e3c333a10d41c8ab150ebee11d2e92") -- fernsehmuell_Reverse_Play_Shuttle_Background.lua if reverse_function ~= 0 then if is_playing_reverse()>0 then reaper.SetProjExtState(0, "Fernsehmuell", "Reverse_Play_Shuttle", 2) --set reverse status to 2 -> button pressed again! else reaper.Main_OnCommand(reverse_function, 0) end else reaper.ShowMessageBox("the script file: "..GetPath(filename).."fernsehmuell_Reverse_Play_Shuttle_Background.lua".. " is missing.", "Warning: LUA Script missing.", 0) end reaper.Undo_EndBlock("PLAY REVERSE fernsehmuell", -1) end main() <file_sep>/Mediacomposer_like_functions/fernsehmuell_GotoIN_(Q).lua -- @version 1.0 -- @author <NAME> -- @changelog -- Initial release function main() playstate=reaper.GetPlayState() --0 stop, 1 play, 2 pause, 4 rec if playstate==1 then reaper.Main_OnCommand(1016,0) end --stop as mediacomposer does (do we need that?) in_pos, out_pos = reaper.GetSet_LoopTimeRange(0,0,0,0,0) -- get start and end point if (in_pos==0.0 and out_pos==0.0) then -- no start point set, OR startpoint is 0.0 -> goto start like avid MC reaper.Main_OnCommand(40042,0) --Transport: Go to start of project (40042) else if (in_pos~=out_pos) then -- start and end point are set reaper.Main_OnCommand(40630,0) --Go to start of time selection else actpos=reaper.GetCursorPosition() reaper.MoveEditCursor(in_pos-actpos, 0) end end end reaper.defer(main) -- run without generating an undo point <file_sep>/Mediacomposer_like_functions/fernsehmuell_SetIN_(i).lua -- @version 1.0 -- @author <NAME> -- @changelog -- Initial release function clear_all_in_markers() retval, marker_count, regions_count = reaper.CountProjectMarkers(0) -- get number of markers for i=marker_count-1,0,-1 do -- count backwards, so numbering of markers does not change! index, isrgn, pos, rgnend, name, markrgnindex = reaper.EnumProjectMarkers2(0, i) -- get name of marker i if name == " [ in" then reaper.DeleteProjectMarkerByIndex(0, index-1) -- delete marker if it is an IN marker end end end function get_position() playstate=reaper.GetPlayState() --0 stop, 1 play, 2 pause, 4 rec possible to combine bits if playstate==1 or playstate==4 then return reaper.GetPlayPosition() else return reaper.GetCursorPosition() end end function main() reaper.Undo_BeginBlock() position=get_position() if position==0 then reaper.SetProjExtState(0, "Fernsehmuell", "StartpointIsZero", "True") -- Set IN-Point is Zero datastore value end in_pos, out_pos = reaper.GetSet_LoopTimeRange(0,0,0,0,0) --get start and end point retval, out_before_in = reaper.GetProjExtState(0, "Fernsehmuell", "End_Point_before_Start_Point") --check if there is an OUT-Point in the datastore if (out_before_in ~= "") then out_pos=tonumber(out_before_in) end -- if there is an OUT in the datastore, then use that one if (out_pos>position) then reaper.SetProjExtState(0, "Fernsehmuell", "End_Point_before_Start_Point", "") -- clear datastore Value retval, retval2 = reaper.GetSet_LoopTimeRange(1,0,position,out_pos,0) else reaper.SetProjExtState(0, "Fernsehmuell", "End_Point_before_Start_Point", out_pos) retval, retval2 = reaper.GetSet_LoopTimeRange(1,0,position,position,0) end clear_all_in_markers() reaper.AddProjectMarker2(0, false, position, 0, " [ in", 0, 0xFFFF00|0x1000000) -- set marker reaper.Undo_EndBlock("Set IN (fernsehmuell script)", -1) end main() <file_sep>/Mediacomposer_like_functions/fernsehmuell_Clear_OUT_Marks_(F).lua -- @version 1.0 -- @author <NAME> -- @changelog -- Initial release function main() reaper.Undo_BeginBlock() in_pos, out_pos = reaper.GetSet_LoopTimeRange(0,0,0,0,0) --get start and end point reaper.SetProjExtState(0, "Fernsehmuell", "End_Point_before_Start_Point", "") -- clear OUT-Point datastore Value retval, retval2 = reaper.GetSet_LoopTimeRange(1,0,in_pos,in_pos,0) -- clear out (set to same position as in point) retval, marker_count, regions_count = reaper.CountProjectMarkers(0) -- get number of markers for i=marker_count-1,0,-1 do -- count backwards, so numbering of markers does not change! index, isrgn, pos, rgnend, name, mindex = reaper.EnumProjectMarkers2(NULL, i) -- get name of marker i if name == " out ]" then reaper.DeleteProjectMarkerByIndex(0, index-1) -- delete marker if it is an OUT marker end end reaper.Undo_EndBlock("Clear OUT marks (fernsehmuell script)", -1) end main() <file_sep>/Mediacomposer_like_functions/fernsehmuell_Extract_(X).lua -- @version 1.0 -- @author <NAME> -- @changelog -- Initial release function clear_all_in_and_out_markers() reaper.Main_OnCommand(40635,0) -- Time selection: Remove time selection (40635) reaper.SetProjExtState(0, "Fernsehmuell", "StartpointIsZero", "False") -- clear IN-Point is Zero datastore value reaper.SetProjExtState(0, "Fernsehmuell", "End_Point_before_Start_Point", "") -- clear OUT-Point datastore value retval, marker_count, regions_count = reaper.CountProjectMarkers(0) -- get number of markers for i=marker_count-1,0,-1 do -- count backwards, so numbering of markers does not change! index, isrgn, pos, rgnend, name, markrgnindex = reaper.EnumProjectMarkers2(0, i) -- get name of marker i if name == " [ in" or name == " out ]" then reaper.DeleteProjectMarkerByIndex(0, index-1) -- delete marker if it is a IN or OUT marker end end end function there_are_in_and_out_points() in_pos, out_pos = reaper.GetSet_LoopTimeRange(0,0,0,0,0) --get start and end point retval, out_before_in = reaper.GetProjExtState(0, "Fernsehmuell", "End_Point_before_Start_Point") --check if there is an OUT-Point in the datastore if (out_before_in ~= "") then out_pos=tonumber(out_before_in) end -- if there is an OUT in the datastore, then use that one if out_pos==in_pos and out_pos>0 then out_pos=out_pos+1 end -- if IN and OUT are on the end we need this hack return in_pos~=out_pos end function goto_in() playstate=reaper.GetPlayState() --0 stop, 1 play, 2 pause, 4 rec if playstate==1 then reaper.Main_OnCommand(1016,0) end --stop as mediacomposer does (do we need that?) in_pos, out_pos = reaper.GetSet_LoopTimeRange(0,0,0,0,0) -- get start and end point if (in_pos==0.0 and out_pos==0.0) then -- no start point set, OR startpoint is 0.0 -> goto start like avid MC reaper.Main_OnCommand(40042,0) --Transport: Go to start of project (40042) else if (in_pos~=out_pos) then -- start and end point are set reaper.Main_OnCommand(40630,0) --Go to start of time selection else actpos=reaper.GetCursorPosition() reaper.MoveEditCursor(in_pos-actpos, 0) end end end function main_selected_tracks() reaper.Undo_BeginBlock() --safe ripple mode toggle_state=reaper.GetToggleCommandState(40311) toggle_state_one=reaper.GetToggleCommandState(40310) goto_in() --move cursor to IN point --lift to clear area: reaper.Main_OnCommand(40309,0) -- Set ripple editing off reaper.Main_OnCommand(40289,0) -- unselect all items reaper.Main_OnCommand(40718,0) -- Item: Select all items on selected tracks in current time selection if reaper.CountSelectedMediaItems(0) > 0 then reaper.Main_OnCommand(40312,0) -- Item: Remove selected area of items end in_pos, out_pos = reaper.GetSet_LoopTimeRange(0,0,0,0,0) -- get start and end point --loop through all selected tracks and move all clips right from outpoint for t=1,reaper.CountSelectedTracks(0),1 do Track= reaper.GetSelectedTrack(0,t-1) --get a selected track items_count=reaper.GetTrackNumMediaItems(Track) --count items in track StartPos=0 for i=1,items_count,1 do mediaitem=reaper.GetTrackMediaItem(Track, i-1) StartPos=reaper.GetMediaItemInfo_Value(mediaitem, "D_POSITION") if StartPos>=in_pos then -- move if right from out reaper.SetMediaItemInfo_Value(mediaitem,"D_POSITION",StartPos-(out_pos-in_pos)) end end end --restore ripple mode reaper.Main_OnCommand(40309,0) -- Set ripple editing off if toggle_state==1 then reaper.Main_OnCommand(40311,0) -- Set ripple editing all tracks elseif toggle_state_one==1 then reaper.Main_OnCommand(40310,0) -- Set ripple editing per track end clear_all_in_and_out_markers() reaper.Main_OnCommand(40289,0) -- unselect all items reaper.Undo_EndBlock("Lift (fernsehmuell script)", -1) end function main() if there_are_in_and_out_points() and out_before_in == "" then if reaper.CountSelectedTracks(0)==0 or reaper.CountTracks(0)==0 then -- if no (selected) tracks just leave else main_selected_tracks() end end end reaper.runloop(main) <file_sep>/Mediacomposer_like_functions/fernsehmuell_GotoOUT_(W).lua -- @version 1.0 -- @author <NAME> -- @changelog -- Initial release function main() playstate=reaper.GetPlayState() --0 stop, 1 play, 2 pause, 4 rec if playstate==1 then reaper.Main_OnCommand(1016,0) end --stop as mediacomposer does (do we need that?) in_pos, out_pos = reaper.GetSet_LoopTimeRange(0,0,0,0,0) --get start and end point retval, out_before_in = reaper.GetProjExtState(0, "Fernsehmuell", "End_Point_before_Start_Point") --check if there is an OUT-Point in the datastore if (in_pos~=out_pos) then -- there is a "normal" OUT point reaper.MoveEditCursor(out_pos-reaper.GetCursorPosition(), 0) elseif (out_before_in ~= "") then -- there is a stored OUT point reaper.MoveEditCursor(tonumber(out_before_in)-reaper.GetCursorPosition(), 0) else reaper.Main_OnCommand(40043,0) --there is no outpoint just go to the end end end reaper.defer(main) -- run without generating an undo point <file_sep>/Mediacomposer_like_functions/fernsehmuell_Forward_Play_Shuttle_(L).lua -- @version 1.0 -- @author <NAME> -- @changelog -- Initial release function incr_pbrate(n) -- increase rate ~6% n times n=math.min(n,200) -- limit n to 200 for i=1, n, 1 do reaper.Main_OnCommand(40522, 0) -- incr playrate by ~6% end end function is_playing_reverse() retval,value=reaper.GetProjExtState(0, "Fernsehmuell", "Reverse_Play_Shuttle") --check if reverse playing if not tonumber(value) then value="0" end if value=="1" then return 1 elseif value=="2" then return 2 else return 0 end end function stop_reverse_loop() reaper.SetProjExtState(0, "Fernsehmuell", "Reverse_Play_Shuttle", 3) -- store state in datastore, no reverse play end function init_function() reaper.Undo_BeginBlock() if is_playing_reverse()>0 then stop_reverse_loop() return 5 end --reaper.defer(stop_reverse_loop) end playstate=reaper.GetPlayState() --0 stop, 1 play, 2 pause, 4 rec possible to combine bits if playstate==1 then -- reaper is playing playrate=reaper.Master_GetPlayRate(0) -- read playrate if playrate<1 then reaper.CSurf_OnPlayRateChange(1.0) end -- if rate<1 set playrate=1 if math.floor(playrate+0.5)==1 then reaper.CSurf_OnPlayRateChange(2.0) end -- if rate is 1x incr to 2x if math.floor(playrate+0.5)==2 then reaper.CSurf_OnPlayRateChange(3.0) end -- if rate is 2x incr. to ~3x if math.floor(playrate+0.5)==3 then reaper.CSurf_OnPlayRateChange(3.9685) reaper.defer(incr_pbrate(4)) end -- if rate is 3x incr. to ~5x if math.floor(playrate+0.5)==5 then reaper.CSurf_OnPlayRateChange(4.0) reaper.defer(incr_pbrate(12)) end -- if rate is 5x incr. to ~8x elseif playstate==0 or playstate==2 then -- reaper ist paused or stopped reaper.CSurf_OnPlayRateChange(1.0) reaper.Main_OnCommand(1007,0) -- play end reaper.Undo_EndBlock("PLAY fernsehmuell", -1) return 1 end function get_last_timecode() -- get last timecode of whole project (is there an easier way???) last_tc=0 for t=1, reaper.GetNumTracks(),1 do Track= reaper.GetTrack(0,t-1) --get track if reaper.GetTrackNumMediaItems(Track)>0 then mediaitem=reaper.GetTrackMediaItem(Track, reaper.GetTrackNumMediaItems(Track)-1) -- get last item in_point=reaper.GetMediaItemInfo_Value(mediaitem, "D_POSITION") out_point=in_point + reaper.GetMediaItemInfo_Value(mediaitem, "D_LENGTH") if out_point>last_tc then last_tc=out_point end end end return last_tc end function runloop() playstate=reaper.GetPlayState() if playstate==1 then -- if playing restart loop reaper.defer(runloop) end if playstate==0 or playstate==2 then -- STOP/PAUSE -> change playrate to 1 and reset all undo points if reaper.GetPlayPosition()+0.3 >=get_last_timecode() then reaper.Main_OnCommand(40043,0) end reaper.CSurf_OnPlayRateChange(1) undo_done=0 while reaper.Undo_CanUndo2(0)=="PLAY fernsehmuell" or reaper.Undo_CanUndo2(0)=="Playrate Change" do reaper.Undo_DoUndo2(0) end end end if init_function()==1 then --if rev=1 run loop, else just leave (ending loop) reaper.defer(runloop) -- run without generating an undo point end <file_sep>/Mediacomposer_like_functions/fernsehmuell_Lift_(Y).lua -- @version 1.0 -- @author <NAME> -- @changelog -- Initial release function goto_in() playstate=reaper.GetPlayState() --0 stop, 1 play, 2 pause, 4 rec if playstate==1 then reaper.Main_OnCommand(1016,0) end --stop as mediacomposer does (do we need that?) in_pos, out_pos = reaper.GetSet_LoopTimeRange(0,0,0,0,0) -- get start and end point if (in_pos==0.0 and out_pos==0.0) then -- no start point set, OR startpoint is 0.0 -> goto start like avid MC reaper.Main_OnCommand(40042,0) --Transport: Go to start of project (40042) else if (in_pos~=out_pos) then -- start and end point are set reaper.Main_OnCommand(40630,0) --Go to start of time selection else actpos=reaper.GetCursorPosition() reaper.MoveEditCursor(in_pos-actpos, 0) end end end function main() reaper.Undo_BeginBlock() toggle_state=reaper.GetToggleCommandState(40311) toggle_state_one=reaper.GetToggleCommandState(40310) reaper.Main_OnCommand(40309,0) -- Set ripple editing off reaper.Main_OnCommand(40289,0) -- unselect all items reaper.Main_OnCommand(40718,0) -- Item: Select all items on selected tracks in current time selection if reaper.CountSelectedMediaItems(0) > 0 then reaper.Main_OnCommand(40312,0) -- Item: Remove selected area of items end if toggle_state==1 then reaper.Main_OnCommand(40311,0) -- Set ripple editing all tracks elseif toggle_state_one==1 then reaper.Main_OnCommand(40310,0) -- Set ripple editing on selected tracks end reaper.Main_OnCommand(40289,0) -- unselect all items goto_in() reaper.Undo_EndBlock("Lift (fernsehmuell script)", -1) end main() <file_sep>/README.md # Fernsehmüll Reaper Scripts Collection of my Reaper Scripts ## Avid Media Composer like keyboard functions ### IN and OUT Marks * SetIN_(i): Sets IN mark at cursor position * SetOUT_(O): Sets OUT mark at cursor position * MarkClip_(T): Mark clip/region in selected Tracks, if no track is selected use all tracks * GotoIN_(Q): Goto IN mark * GotoOUT_(W): Goto OUT mark * Clear_Both_Marks_(G): Clear IN and OUT mark * Clear_IN_Marks_(D): Clear IN mark * Clear_OUT_Marks_(F): Clear OUT mark ###Edit * Add_Edit_(S): like the Reaper Split function, but this does not split locked items. And it does not mark any items. (you can change this behavior by changing to variables in the script) * Extract_(X): Extract time selection on selected tracks * Lift_(Y): Lift time selection on selected tracks ###Navigate * Reverse_Play_Shuttle_(J): Move cursor backwards, press multiple times to increase speed * Reverse_Play_Shuttle_Background: Background function used by Reverse_Play_Shuttle_(J) (don't rename this file!) * Pause_(K): Pause * Forward_Play_Shuttle_(L): Play forwards, press multiple times to increase speed * Step_backwards_40ms_(3): Step backwards 40ms (1 video frame @25fps) * Step_backwards_400ms_(1): Step backwards 400ms (10 video frames @25fps) * Step_forwards_40ms_(4): Step forwards 40ms (1 video frame @25fps) * Step_backwards_400ms_(2): Step forwards 400ms (10 video frame @25fps) * Go_to_next_event: Move cursor to next event in selected tracks. If no track is selected move to next event in all tracks * Go_to_prev_event: Move cursor to previous event in selected tracks. If no track is selected move to previous event in all tracks ##Installation Copy the .lua files to your Reaper scripts directory or any other directory you like. In Reaper choose Actions/Show actions list... Press the "Load..." button on the lower right side. Select all of the fernsehmuell_ scripts and press Open/Enter. You can find the scripts in the action list under: Script: fernsehmuell_... Now assign Keyboardshortcuts to each script ("Add..." button) The recommended key is the letter in () at the end of the filename. If you use the Forward_Play_Shuttle_(L) for the first time a "ReaScript task control" window pops up. Check the checkbox and press "New instance" <file_sep>/Mediacomposer_like_functions/fernsehmuell_Go_to_next_event.lua -- @version 1.0 -- @author <NAME> -- @changelog -- Initial release reaper.Main_OnCommand(1016, 0) -- stop playback timecodes={} -- array holding all edit timecodes tracks_count=reaper.GetNumTracks() selected_tracks_count=reaper.CountSelectedTracks(0) pos=reaper.GetCursorPosition() if selected_tracks_count>0 then --find events (start/end of items) for t=1,selected_tracks_count,1 do Track= reaper.GetSelectedTrack(0,t-1) --get a selected track items_count=reaper.GetTrackNumMediaItems(Track) --count items in track --analyse this track (collect all start and end points of all items) for i=1,items_count,1 do mediaitem=reaper.GetTrackMediaItem(Track, i-1) in_point=reaper.GetMediaItemInfo_Value(mediaitem, "D_POSITION") out_point=in_point + reaper.GetMediaItemInfo_Value(mediaitem, "D_LENGTH") table.insert(timecodes,in_point) table.insert(timecodes,out_point) end end table.sort(timecodes) -- sort timecodes for i, tc in ipairs(timecodes) do -- search first timecode>cursor pos, then jump to that tc and end if tc>pos then reaper.MoveEditCursor(tc-pos, 0) return 1 end end else reaper.Main_OnCommand(41168, 0) end <file_sep>/Mediacomposer_like_functions/fernsehmuell_Reverse_Play_Shuttle_Background.lua -- @version 1.0 -- @author <NAME> -- @changelog -- Initial release debug=false function dbg(text) if debug then reaper.ShowConsoleMsg(tostring(text).."\n") end end function get_position() playstate=reaper.GetPlayState() --0 stop, 1 play, 2 pause, 4 rec possible to combine bits if playstate==1 or playstate==4 then return reaper.GetPlayPosition() else return reaper.GetCursorPosition() end end function is_playing_reverse() retval,value=reaper.GetProjExtState(0, "Fernsehmuell", "Reverse_Play_Shuttle") --check if reverse playing if not tonumber(value) then value="0" end if value=="1" then return 1 elseif value=="2" then return 2 elseif value=="3" then return 3 else return 0 end end function get_last_timecode() -- get last timecode of whole project (is there an easier way???) last_tc=0 for t=1, reaper.GetNumTracks(),1 do Track= reaper.GetTrack(0,t-1) --get track if reaper.GetTrackNumMediaItems(Track)>0 then mediaitem=reaper.GetTrackMediaItem(Track, reaper.GetTrackNumMediaItems(Track)-1) -- get last item in_point=reaper.GetMediaItemInfo_Value(mediaitem, "D_POSITION") out_point=in_point + reaper.GetMediaItemInfo_Value(mediaitem, "D_LENGTH") if out_point>last_tc then last_tc=out_point end end end return last_tc end function check_position() --check if cursor is past the last edit, if so goto to lastedit -0.1 sec. start_position=get_position() --get cursor position end_position=get_last_timecode() if start_position>=end_position then start_position=math.max(0,end_position-0.1) end reaper.MoveEditCursor(start_position-get_position(),0) end function init() ignoreonexit=0 speed_list = {1,2,3,5,8} max_speed=#speed_list speed=1 reaper.Main_OnCommand(40521, 0) -- set play speed to 1 reaper.SetProjExtState(0, "Fernsehmuell", "Reverse_Play_Shuttle", 1) -- store state in datastore starttime=reaper.time_precise() --get actual time check_position() reaper.OnPlayButton() dbg("init_ende") end function onexit() if ignoreonexit==0 then reaper.SetProjExtState(0, "Fernsehmuell", "Reverse_Play_Shuttle", 0) -- store state in datastore reaper.Main_OnCommand(40521, 0) -- set play speed to 1 reaper.Main_OnCommand(1007,0) --play reaper.Main_OnCommand(1008,0) --pause reaper.Main_OnCommand(1016,0) --stop end while reaper.Undo_CanUndo2(0)=="PLAY REVERSE fernsehmuell" or reaper.Undo_CanUndo2(0)=="Playrate Change" or reaper.Undo_CanUndo2(0)=="Set project playspeed"do reaper.Undo_DoUndo2(0) end end function runloop() --BACKGROUND Loop playstate= reaper.GetPlayState()==1 or reaper.GetPlayState()==2 dbg(playstate) dbg(is_playing_reverse()) if is_playing_reverse()==2 then --increase speed speed=math.min(speed+1, max_speed) starttime=reaper.time_precise() --get actual time after speedchange! reaper.SetProjExtState(0, "Fernsehmuell", "Reverse_Play_Shuttle", 1) -- store state in datastore start_position=get_position() reaper.Main_OnCommand(1008,0) --pause end if is_playing_reverse()==1 and playstate and reaper.GetCursorPosition()>0 then --reverse playing -> move cursor time_passed=(reaper.time_precise()-starttime) * speed_list[speed] reaper.MoveEditCursor(start_position-time_passed-reaper.GetCursorPosition(), 0) reaper.OnPlayButton() reaper.CSurf_OnPlayRateChange(1.0+speed_list[speed]/10000.0) reaper.defer(runloop) -- restart loop end if is_playing_reverse()==3 then --play was pressed: stop reverse playing and play forward reaper.Main_OnCommand(40521, 0) -- set play speed to 1 reaper.SetProjExtState(0, "Fernsehmuell", "Reverse_Play_Shuttle", 0) -- store state in datastore reaper.Main_OnCommand(1008,0) --pause reaper.Main_OnCommand(1016,0) --stop reaper.OnPlayButton() --play ignoreonexit=1 end end init() reaper.atexit(onexit) reaper.defer(runloop) <file_sep>/Mediacomposer_like_functions/fernsehmuell_Clear_Both_Marks_(G).lua -- @version 1.0 -- @author <NAME> -- @changelog -- Initial release function clear_all_in_and_out_markers() retval, marker_count, regions_count = reaper.CountProjectMarkers(0) -- get number of markers for i=marker_count-1,0,-1 do -- count backwards, so numbering of markers does not change! index, isrgn, pos, rgnend, name, markrgnindex = reaper.EnumProjectMarkers2(0, i) -- get name of marker i if name == " [ in" or name == " out ]" then reaper.DeleteProjectMarkerByIndex(0, index-1) -- delete marker if it is a IN or OUT marker end end end function there_are_in_and_out_points() in_pos, out_pos = reaper.GetSet_LoopTimeRange(0,0,0,0,0) --get start and end point retval, isstartpointzero = reaper.GetProjExtState(0, "Fernsehmuell", "StartpointIsZero") --check if there is an OUT-Point in the datastore if isstartpointzero~="" then if isstartpointzero=="True" then in_pos=0 end end retval, out_before_in = reaper.GetProjExtState(0, "Fernsehmuell", "End_Point_before_Start_Point") --check if there is an OUT-Point in the datastore if (out_before_in ~= "") then out_pos=tonumber(out_before_in) end -- if there is an OUT in the datastore, then use that one if out_pos==in_pos and out_pos>0 then out_pos=out_pos+1 end -- if IN and OUT are on the end we need this hack if in_pos==0 and out_pos==0 then out_pos=1 end return in_pos~=out_pos end function main() reaper.Undo_BeginBlock() if reaper.GetPlayState()==1 then --stop as mediacomposer does (do we need that?) reaper.Main_OnCommand(1008,0) reaper.Main_OnCommand(1016,0) end reaper.Main_OnCommand(40635,0) -- Time selection: Remove time selection (40635) reaper.SetProjExtState(0, "Fernsehmuell", "StartpointIsZero", "False") -- clear IN-Point is Zero datastore value reaper.SetProjExtState(0, "Fernsehmuell", "End_Point_before_Start_Point", "") -- clear OUT-Point datastore value clear_all_in_and_out_markers() reaper.Undo_EndBlock("Clear both marks (fernsehmuell script)", -1) end if there_are_in_and_out_points() then main() end
3cac163bb9fcb984617d64803cf3a7455883b731
[ "Markdown", "Lua" ]
17
Lua
fernsehmuell/reaper_scripts
fbe1d6d95b4bcd4d30dee3738aa9738f9470aee9
8944b7eab7f4203abf9e9e55e4f795fc46a91288
refs/heads/master
<repo_name>masven2/aepoo<file_sep>/AEP_1.2/src/AEP/Conceito.java package AEP; import java.util.List; import java.util.ArrayList; public class Conceito { private final String id; private List<Aluno> alunos = new ArrayList<Aluno>(); private List<Avaliação> avaliaçoes = new ArrayList<Avaliação>(); private List<Nota> notas = new ArrayList<Nota>(); public Conceito(String id) { if (id == null || id.trim().length()==0) { throw new RuntimeException("Id não pode ser nulo nem vazio!"); } else { this.id = id; } } public void addAluno (Aluno alunos) { if(!this.alunos.contains(alunos)) { this.alunos.add(alunos); } } public void addAvaliação (Avaliação avaliaçoes) { if(!this.avaliaçoes.contains(avaliaçoes)) { this.avaliaçoes.add(avaliaçoes); } } public void addNota(Nota notas) { if(!this.notas.contains(notas)) { this.notas.add(notas); } } public List<Aluno> getAlunos(){ return alunos; } public List<Avaliação> getAvaliações(){ return avaliaçoes; } public List<Nota> getNota(){ return notas; } public String getId(){ return id; } } <file_sep>/AEP_1.2/src/AEP/Avaliação.java package AEP; public class Avaliação { private String disciplina; public Avaliação(String disciplina) { this.disciplina = disciplina; this.setDisciplina(disciplina); } public String getDisciplina() { return this.disciplina; } public void setDisciplina(String disciplina) { this.disciplina = disciplina; } }
5e05d2295d5172c995056fa92c590695bc46d983
[ "Java" ]
2
Java
masven2/aepoo
f8998e37b48215a5e69b3ce3aca2e49cee012307
88f7b98a87ff0447916f10d8d860bbffc0775ff9
refs/heads/master
<file_sep>module.exports = function(context) { console.log('=== Compiling CSS ==='); var fs = context.requireCordovaModule('fs'); var path = context.requireCordovaModule('path'); var deferral = context.requireCordovaModule('q').defer(); var sass = require('node-sass'); var inputFile = path.join(context.opts.projectRoot, 'src/stylesheets/index.scss'); var outputFile = path.join(context.opts.projectRoot, 'www/css/index.css'); sass.render({ file: inputFile }, function(err, result) { if(err) { console.log(err); } fs.writeFile(outputFile, result.css.toString(), function(err) { if(err) { console.log(err); } deferral.resolve(); }); }); return deferral.promise; }; <file_sep>module.exports = function(context) { console.log('=== Compiling HTML ==='); var fs = context.requireCordovaModule('fs'); var path = context.requireCordovaModule('path'); var deferral = context.requireCordovaModule('q').defer(); var ejs = require('ejs'); var inputFile = path.join(context.opts.projectRoot, 'src/index.html'); var outputFile = path.join(context.opts.projectRoot, 'www/index.html'); fs.readFile(inputFile, function(err, content) { if(err) { console.log(err); } var output = ejs.render(content.toString(), {}, { filename: inputFile }); fs.writeFile(outputFile, output, function(err) { if(err) { console.log(err); } deferral.resolve(); }); }); return deferral.promise; }; <file_sep># My personal Cordova/Phonegap hooks That's a collection of Cordova hooks I use. It is needed to install the packages listed on `package.json` and add the hooks on your `config.xml`. Example: ```xml <hook src="scripts/compile_js.js" type="before_compile" /> ```
05f11985f6d894d4f86f5c2fa8719a28b0bb6428
[ "JavaScript", "Markdown" ]
3
JavaScript
talyssonoc/cordova-hooks
6d6dd4d05b840b97176175e35799c2a791dbaa0c
61455943dc685cd2bc11d3efc2656545a3fbcd61
refs/heads/main
<repo_name>kronik-coder/react-store-project<file_sep>/src/components/NavBar.js import React, { Component } from 'react' import {Navbar, Container, Nav} from 'react-bootstrap' import {Link} from 'react-router-dom' export default class NavBar extends Component { render() { return ( <Navbar bg="dark" variant="dark" expand="lg" style={{ marginBottom:"20px" }} sticky="top"> <Container> <Navbar.Brand target="_blank" href="https://www.youtube.com/watch?v=zhf1pIl007o&list=LL&index=1">FakeShop</Navbar.Brand> <Navbar.Toggle aria-controls="basic-navbar-nav" /> <Navbar.Collapse id="basic-navbar-nav"> <Nav className="me-auto"> <Nav.Link as={Link} to="/">Home</Nav.Link> <Nav.Link as={Link} to="Cart">Cart</Nav.Link> <Nav.Link as={Link} to="Logout">Logout</Nav.Link> <Nav.Link as={Link} to="Login">Login</Nav.Link> </Nav> </Navbar.Collapse> </Container> </Navbar> ) } }<file_sep>/src/views/Home.js import React, { Component } from 'react' import { Card, Button } from 'react-bootstrap' export default class Home extends Component { constructor(){ super(); this.state = { myItem: {} } } render() { return ( <div style={{display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between'}}> {this.props.items.map( item => ( <Card style={{ width: '18rem' }}> <Card.Img variant="top" src={item.image} height='300px'/> <Card.Body> <Card.Title style={{fontWeight: 'bold'}}>{item.title}</Card.Title> <Card.Text style={{fontWeight: 'bold'}}>{item.category}</Card.Text> <Card.Text> {item.description} </Card.Text> <Card.Text>${item.price}</Card.Text> <Button variant="primary" onClick={()=>{ this.setState({myItem: {title: item.title, price: item.price, image: item.image}}) this.props.addToCart(this.state.myItem) console.log(this.state.myItem) }}>ADD</Button> </Card.Body> </Card> ) )} </div> ) } } <file_sep>/src/App.js import React, { Component } from 'react' import {Routes, Route} from 'react-router-dom' import Home from './views/Home' import Cart from './views/Cart' import Login from './views/Login' import 'bootstrap/dist/css/bootstrap.min.css'; import NavBar from './components/NavBar'; import axios from 'axios'; export default class App extends Component { constructor(){ super() this.state={ items: [], token: '', myItems: [] } } addToCart = (myItem)=>{ let myItems = this.state.myItems myItems.push(myItem) this.setState(myItems) console.log(myItems) } render() { axios.get('https://fakestoreapi.com/products?limit=15').then(({data})=>{ this.setState({items: data}) }) return ( <div> <NavBar items={this.state.items} token={this.state.token}/> <Routes> <Route path='/' element={<Home items={this.state.items} addToCart={this.addToCart}/>} /> <Route path='/cart' element={<Cart myItems={this.state.myItems}/>} /> <Route path='/login' element={<Login />} /> </Routes> </div> ) } } <file_sep>/src/views/Cart.js import React, { Component } from 'react' import { Card } from 'react-bootstrap' export default class Cart extends Component { render() { return ( <div style={{display: 'flex', flexWrap: 'wrap', justifyContent: 'space-around', textAlign: 'center'}}> <p className="form-control" style={{fontSize: '50px', fontWeight: 'bold'}}>Your Items</p> {this.props.myItems.map( item => ( <Card style={{ width: '18rem' }}> <Card.Img variant="top" src={item.image} height='300px'/> <Card.Body> <Card.Title style={{fontWeight: 'bold'}}>{item.title}</Card.Title> <Card.Text style={{fontWeight: 'bold'}}>{item.category}</Card.Text> <Card.Text> {item.description} </Card.Text> <Card.Text>${item.price}</Card.Text> </Card.Body> </Card> ) )} </div> ) } }
68ce8aadf3b5ad0ff74862ae9b4ce58766c16d5f
[ "JavaScript" ]
4
JavaScript
kronik-coder/react-store-project
11942093dfeeb5c2cf42cc074df99e1d455ca9ae
0746861abfff2eea2283887565fb222053e02393
refs/heads/main
<file_sep>import { Component } from "react"; import { ImSearch } from "react-icons/im"; import { toast } from "react-toastify"; const styles = { form: { marginBottom: 20 } }; export default class PokemonForm extends Component { state = { pokemonName: "", }; handleNameChange = (event) => { this.setState({ pokemonName: event.currentTarget.value.toLowerCase() }); }; handleSubmit = (event) => { event.preventDefault(); if (this.state.pokemonName.trim() === "") { return toast.error("Ведите имя покемона!"); } this.props.onSubmit(this.state.pokemonName); this.setState({ pokemonName: "" }); }; render() { return ( <form onSubmit={this.handleSubmit} style={styles.form}> <input type="text" name="pokemon" value={this.state.pokemonName} onChange={this.handleNameChange} /> <button type="submit"> <ImSearch style={{ marginRight: 8 }} /> Найти </button> </form> ); } } <file_sep>import "./App.css"; import React, { Component } from "react"; import { ToastContainer } from "react-toastify"; import PokemonForm from "./components/PokemonForm"; import PokemonInfo from "./components/PokemonInfo"; // import Clock from './components/Clock/Clock'; // import Modal from './components/Modal'; // import Tabs from './components/Tabs/Tabs'; export default class App extends Component { state = { pokemonName: "", }; handleFormSubmit = (pokemonName) => { this.setState({ pokemonName }); }; render() { return ( <div style={{ maxWidth: 1170, margin: "0 auto", padding: 20 }}> <PokemonForm onSubmit={this.handleFormSubmit} /> <PokemonInfo pokemonName={this.state.pokemonName} /> <ToastContainer autoClose={3000} /> </div> ); } } /* state = { pokemon: null, loading: false, }; componentDidMount() { this.setState({ loading: true }); setTimeout(() => { fetch('https://pokeapi.co/api/v2/pokemon/ditto') .then(res => res.json()) .then(pokemon => this.setState({ pokemon })) .finally(() => this.setState({ loading: false })); }, 1000); } {this.state.loading && <h1>Загружаем...</h1>} {this.state.pokemon && <div>{this.state.pokemon.name}</div>} */ /* <Tabs /> class App extends Component { state = { todos: [], filter: '', showModal: false, }; toggleModal = () => { this.setState(({ showModal }) => ({ showModal: !showModal, })); } render() { const { todos, filter, showModal } = this.state; return ( <div className="App"> <button type="button" onClick={this.toggleModal}> Открыть модалку </button> {showModal && ( <Modal onClose={this.toggleModal}> <h1>Контент модалки как children</h1> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> <button type="button" onClick={this.toggleModal}> Закрыть </button> </Modal> )} <Clock /> </div> ); } } */ <file_sep>function fetchPokemon(name) { return fetch(`https://pokeapi.co/api/v2/pokemon/${name}`).then((response) => { if (response.ok) { return response.json(); } return Promise.reject(new Error(`Нет покемона с именем "${name}".`)); }); } const pokemonAPI = { fetchPokemon, }; export default pokemonAPI; <file_sep>import { Component } from "react"; import PokemonErrorView from "./PokemonErrorView"; import PokemonDataView from "./PokemonDataView"; import PokemonPendingView from "./PokemonPendingView"; import pokemonAPI from "./services/pokemon-api"; export default class PokemonInfo extends Component { state = { pokemon: null, status: "idle", error: null, }; componentDidUpdate(prevProps, prevState) { const prevName = prevProps.pokemonName; const nextName = this.props.pokemonName; if (prevName !== nextName) { this.setState({ status: "pending" }); pokemonAPI .fetchPokemon(nextName) .then((pokemon) => this.setState({ pokemon, status: "resolved" })) .catch((error) => this.setState({ error, status: "rejected" })); } } render() { const { pokemon, error, status } = this.state; const { pokemonName } = this.props; if (status === "idle") { return <div>Type pokemon name</div>; } if (status === "pending") { return <PokemonPendingView pokemonName={pokemonName} />; } if (status === "rejected") { return <PokemonErrorView message={error.message} />; } if (status === "resolved") { return <PokemonDataView pokemon={pokemon} />; } } } /* render() { const { status, pokemon, error } = this.state; switch(status) { case 'idle': return <h1>Введите имя покемона!</h1>; case 'pending': return <PokemonPendingView pokemonName={this.props.pokemonName} />; case 'rejected': return <PokemonErrorView message={error.message} />; case 'resolved': return <PokemonDataView pokemon={pokemon} />; default: return null; } } if (status === 'resolved') { return ( <div> <p>{pokemon.name}</p> <img src={pokemon.sprites.other['official-artwork']. front_default} alt={pokemon.name} width="240" /> </div> ); } */ <file_sep>import { ImSpinner } from "react-icons/im"; import PokemonDataView from "./PokemonDataView"; import pendingImage from "./pending.webp"; const styles = {}; export default function PokemonPendingView({ pokemonName }) { const pokemon = { name: pokemonName, sprites: { other: { "official-artwork": { front_default: pendingImage, }, }, }, stats: [], }; return ( <div role="alert"> <div style={StyleSheet.spinner}> <ImSpinner size="32" className="icon-spin" /> Loading... </div> <PokemonDataView pokemon={pokemon} /> </div> ); }
c73822471184995914785f7a5673a51e43582883
[ "JavaScript" ]
5
JavaScript
Semivetal/react-35-module-3-main
4d8a1a0979567f8ebd68341b0cbe79f9f00d0053
c5c816d28391b14983074ce20a1a25778561399e
refs/heads/master
<repo_name>ahandsel/youtube_subscription_transfer<file_sep>/README.md # youtube_subscription_transfer * Migrate the subscriptions from a YouTube account to another with Python and [Selenium](https://www.selenium.dev/selenium-ide/) ## Credit: following code was used for this project: * @skhzhang [/youtube_migrate.py](https://gist.github.com/skhzhang/e12195917db5f6bf8c3e6b02cd6a4af2) * @zenwalker[/youtube_migrate.py](https://gist.github.com/zenwalker/0037fff3be1fbdb889bb) ## Step A - Download subscription_manager.xm for old & new YouTube accounts: 1. Login into the **old** YouTube acount that you want to export the subscriptions from. 2. Go to the Manage Subscriptions page: [www.youtube.com/subscription_manager](https://www.youtube.com/subscription_manager) 3. Scroll to the buttom to the **Export to RSS readers** section. 4. On the right, click **Export subscriptions** button. * The OPML file named "subscription_manager.xml" will download. 5. Rename the file as **subscription_manager-source.xml** 6. Repeate for steps 1 to 4 for your **new** YouTube account that you want to import the subscriptions into. * Rename the file as **subscription_manager-destination.xml** ## Step B - Install pyenv & Python * Following assumes MacOS Catalina 1. Install brew | [brew.sh](https://brew.sh/) ```bash /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" ``` 2. Install pyenv | [pyenv Installation](https://github.com/pyenv/pyenv#installation) ```bash brew update brew install pyenv brew install openssl readline sqlite3 xz zlib ``` * Add `pyenv init` to your shell to enable shims and autocompletion. * Please make sure eval "$(pyenv init -)" is placed toward the end of the shell configuration file since it manipulates PATH during the initialization. * For bash: ```bash echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n eval "$(pyenv init -)"\nfi' >> ~/.bash_profile ``` * For zsh: ```zsh echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n eval "$(pyenv init -)"\nfi' >> ~/.zshrc ``` * Restart your shell so the path changes take effect. You can now begin using pyenv. ```bash exec "$SHELL" ``` 3. Install Python using pyenv * Quick list of pyenv commands: | pyenv commands | action | |--|--| | `pyenv install --list` | lists out the python versions | | `pyenv install <version>` | Installs the selected version | | `pyenv versions` | lists out all installed versions| | `pyenv global <version>` | Set the global or default python version | | `pyenv local <version>` | Set the local version by cd'ing into the repo then.. | | `python --version` | Check current python version | * Install [python](https://www.python.org/downloads/) version 3.8.2 and set as the default version ```bash pyenv install 3.8.2 pyenv global 3.8.2 ``` ## Step C - Install Selenium * [Selenium Python Installation](https://selenium-python.readthedocs.io/installation.html) 1. Update pip (you already installed pip when you installed Python version >= 3.4) ```bash pip install --upgrade pip ``` 2. Downloading Python bindings for Selenium ```bash pip install selenium ``` ## Step D - Install FireFox's geckodriver * [geckodriver/releases](https://github.com/mozilla/geckodriver/releases) * Selenium requires a driver to interface with a browser in your PATH (/usr/bin or /usr/local/bin) * Firefox broswer --> requires GeckoDriver driver 1. Under [**Assets**](https://github.com/mozilla/geckodriver/releases), install the geckodriver-v0.26.0-macos.tar.gz 2. Then running the following command to address the [MacOS Notarization](https://firefox-source-docs.mozilla.org/testing/geckodriver/Notarization.html) known problem: * ` xattr -r -d com.apple.quarantine geckodriver-v0.26.0-macos.tar.gz` 3. Run the following in your terminal * `sudo nano /etc/paths` 4. Insert the path to the geckodriver download at the bottom of the file * My PATH is: /Users/beta/Downloads/geckodriver * `control`+`x` to quit * `y` to save * return to confirm * Confirming New PATH: relaunch Terminal and run * `echo $PATH` * Your path to geckodriver should be included in the output 5. Geckodriver executable needs to be in PATH * `sudo cp geckodriver /usr/local/bin` 6. Install [Firefox](https://www.mozilla.org/en-US/firefox/new/) * Firefox 76.0 is used ## Step E - Place the three files in one folder * youtube_migrate.py * subscription_manager-**source**.xml * subscription_manager-***destination***.xml ## Step F - Run script, manually login, and go to drink coffee. * It will take some time. * Note YouTube will temporary block you if you have more that 80 subscriptions. * Just restart the script in a few hours. ## ERROR: selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH. * cd to the folder with the geckodriver and run the following command: `sudo cp geckodriver /usr/local/bin` ## References used: * [Running selenium on MacOS using chromedriver](https://medium.com/@KelvinMwinuka/running-selenium-on-macos-using-chromedriver-96ef851282b5) * [Code documentation on selenium-python](https://selenium-python.readthedocs.io/) * [Set up Selenium & GeckoDriver \(Mac\)](https://medium.com/dropout-analytics/selenium-and-geckodriver-on-mac-b411dbfe61bc) * [The Python virtual environment with Pyenv & Pipenv](https://dev.to/writingcode/the-python-virtual-environment-with-pyenv-pipenv-3mlo) * [How to install and Set up Python on Mac](https://dev.to/brohittv/how-to-install-and-set-up-python-on-mac-29fd?signin=true) * [Python Development on macOS with pyenv](https://medium.com/python-every-day/python-development-on-macos-with-pyenv-2509c694a808) https://addons.mozilla.org/en-GB/firefox/addon/selenium-ide/ export PATH=$PATH:/path/to/directory/of/executable/downloaded/in/previous/step <file_sep>/youtube_migrate.py """ Automatic migration of subscriptions to another YouTube account with Python and Selenium. Tested with: - selenium 3.0 - firefox 49.0 - python 3.5 1. Install selenium from pypi: $ pip install selenium 2. Go to the down of page https://www.youtube.com/subscription_manager and download your current subscriptions feed. Save file as subscription_manager-source.xml. 3 Repeat step 2 for the account you would like to import subscriptions into. Save the file as subscription_manager-destination.xml. 4. Run script, manually login, and go to drink coffee. It will take some time. Note YouTube will temporary block you if you have more that 80 subscriptions. Just restart the script in a few hours. """ from collections import namedtuple from selenium import webdriver from selenium.common.exceptions import ElementNotInteractableException from xml.dom import minidom import time import re def main(): notYetSubscribed = list(set(load_subcriptions('subscription_manager-source.xml')) - set(load_subcriptions('subscription_manager-destination.xml'))) driver = webdriver.Firefox() sign_in(driver) for channel in notYetSubscribed: subscribe(driver, channel) driver.close() def sign_in(driver): driver.get('https://www.youtube.com') input('Please login. Press enter after: ') time.sleep(1) def load_subcriptions(filename): xmldoc = minidom.parse(filename) itemlist = xmldoc.getElementsByTagName('outline') channel_id_regexp = re.compile('channel_id=(.*)$') Channel = namedtuple('Channel', ['id', 'title']) subscriptions = [] for item in itemlist: try: feed_url = item.attributes['xmlUrl'].value channel = Channel(id=channel_id_regexp.findall(feed_url)[0], title=item.attributes['title'].value) subscriptions.append(channel) except KeyError: pass return subscriptions def subscribe(driver, channel): channel_url = 'https://www.youtube.com/channel/' + channel.id driver.get(channel_url) time.sleep(1) try: button = driver.find_element_by_id('subscribe-button') button.click() print('{:.<50}{}'.format(channel.title, 'done')) time.sleep(1) except ElementNotInteractableException as error: # cannot scroll button into view print('{:.<50}{}'.format(channel.title, 'error')) print(error) input('Press enter to proceed: ') time.sleep(1) if __name__ == '__main__': main()<file_sep>/Project_Note.md # YouTube Subscription Transfer Project Notes ## References used: * [Running selenium on MacOS using chromedriver](https://medium.com/@KelvinMwinuka/running-selenium-on-macos-using-chromedriver-96ef851282b5) * [Code documentation on selenium-python](https://selenium-python.readthedocs.io/) * [Set up Selenium & GeckoDriver \(Mac\)](https://medium.com/dropout-analytics/selenium-and-geckodriver-on-mac-b411dbfe61bc) * [The Python virtual environment with Pyenv & Pipenv](https://dev.to/writingcode/the-python-virtual-environment-with-pyenv-pipenv-3mlo) * [How to install and Set up Python on Mac](https://dev.to/brohittv/how-to-install-and-set-up-python-on-mac-29fd?signin=true) https://selenium-python.readthedocs.io/installation.html https://addons.mozilla.org/en-GB/firefox/addon/selenium-ide/ ## Credit: following code was used for this project: * @skhzhang [/youtube_migrate.py](https://gist.github.com/skhzhang/e12195917db5f6bf8c3e6b02cd6a4af2) * @zenwalker[/youtube_migrate.py](https://gist.github.com/zenwalker/0037fff3be1fbdb889bb)
4d690a903f454c081517acdf48b672c69e0b5d1c
[ "Markdown", "Python" ]
3
Markdown
ahandsel/youtube_subscription_transfer
1785488d339bbe7806d4627aa1e4a8a6f26aef6b
986688f197e6f3f33f2714e51e78cb9ea879e47d
refs/heads/master
<repo_name>rodfernandez/angular-seed<file_sep>/app/js/filters/interpolate.js 'use strict'; //myApp.filter('interpolate', function () { // var interpolate = function (text) { // return text.toUpperCase(); // } // // return interpolate; //}); myApp.filter('interpolate', ['version', function (version) { var interpolate = function (text) { return String(text).replace(/\%VERSION\%/mg, version); }; return interpolate; }]); <file_sep>/app/js/services/version.js 'use strict'; myApp.value('version', '0.1'); <file_sep>/app/js/controllers/MyCtrl1.js 'use strict'; myApp.controller('MyCtrl1', function () { var MyCtrl1 = function () { } return MyCtrl1; });
3aa93d349d8f13cc2ff432bf9e63810a787677c3
[ "JavaScript" ]
3
JavaScript
rodfernandez/angular-seed
b7ba33591436963a4585ac34245dd54f8e5a5498
f0468b839c92f6a50d4478e03ec00bf2bf18f5b9
refs/heads/master
<repo_name>juanmarin96/agi-vozip-2019<file_sep>/database.sql create schema if not exists `ayuda-covid` collate utf8_general_ci; use ayuda-covid; create table if not exists solicitudes ( id int auto_increment primary key, cedula varchar(15) not null, edad varchar(2) not null, barrio varchar(15) not null, estado int default 0 not null ); <file_sep>/agi-coronavirus.php #!/usr/bin/php -q <?php require("variables.inc"); set_time_limit(120); $param_error_log = '/tmp/notas.log'; $param_debug_on = 1; require('phpagi.php'); $agi = new AGI(); $agi->answer(); $option = $agi->get_variable('IVR_DIGIT_PRESSED'); $agi->verbose($option); if($option['result'] == "1" && $option['data'] == "1"){ $agi->exec_agi("googletts.agi,\"Por favor digite su número de identificación después del tono\",es"); $id = $agi->get_data('beep', 6000, 10)['result']; $agi->verbose($id); $link = mysql_connect(HOST, USUARIO,CLAVE); mysql_select_db(DB, $link); $result = mysql_query("SELECT cedula FROM solicitudes WHERE cedula='$id'", $link); while ($row = mysql_fetch_array($result)){ $estado = ($row['estado']== 0)? 'Pendiente':'Aprobado'; $agi->exec_agi("googletts.agi,\"La solicitud para la cédula " .$row['cedula']." esta en estado ". $estado." \",es"); sleep(1); $agi->exec_agi("googletts.agi,\"Pronto nos comunicaremos con usted\",es"); } }else{ $agi->exec_agi("googletts.agi,\"Registro en proceso\",es"); sleep(1); $agi->exec_agi("googletts.agi,\"Por favor digite su número de identificación después del tono\",es"); $id = $agi->get_data('beep', 3000, 10)['result']; $agi->exec_agi("googletts.agi,\"Por favor digite su edad después del tono\",es"); $age = $agi->get_data('beep', 3000, 2)['result'];; $hoods = array( '1'=>'*Presione 1 si vive en guayabal', '2'=>'*Presione 2 si vive en el poblado', '3'=>'*Presione 3 si vive en castilla', ); $hood = $agi->menu($hoods, 3000); switch ($hood) { case "1": $hood = "Guayabal"; break; case "2": $hood = "El poblado"; break; case "3": $hood = "Castilla"; break; } $agi->verbose($hood); sleep(1); $sql = "INSERT INTO solicitudes (cedula, edad, barrio) VALUES ('$id', '$age', '$hood')"; $agi->verbose($sql); $link = mysql_connect(HOST, USUARIO,CLAVE); mysql_select_db(DB, $link); if(mysql_query("INSERT INTO solicitudes (cedula, edad, barrio) VALUES ('$id', '$age', '$hood')", $link)){ $agi->exec_agi("googletts.agi,\"Su solicitud ha sido registrada con éxito\",es"); $agi->exec_agi("googletts.agi,\"Pronto nos comunicaremos con usted\",es"); } } $agi->exec_agi("googletts.agi,\"Gracias por utilizar el sitema de ayuda por Covid 19\",es"); $agi->exec_agi("googletts.agi,\"Hasta pronto\",es"); $agi->hangup();<file_sep>/variables.inc <?php define("HOST","localhost"); define("USUARIO","root"); define("CLAVE","Voip2019-2"); define("DB","ayuda-covid"); ?>
d156249c393a54bf000e23b077682f0baf80b695
[ "SQL", "PHP" ]
3
SQL
juanmarin96/agi-vozip-2019
1eefaa31ab2c5140a2d574046a9c2e14dc9cee24
ccbc318c2ed8094a9424639bbac4dc8999a97efe
refs/heads/main
<file_sep>/** * @typedef {import('mdast').Root} Root * * @callback TextrPlugin * A textr plugin. * @param {string} value * Value to transform. * @param {object} [options] * Global configuration passed to textr. * @returns {string|void} * Changed text (optional). * * @typedef Options * Configuration. * @property {Array.<string|TextrPlugin>} [plugins] * Textr plugins. * @property {object} [options] * Configuration passed to `textr`. */ import {visit} from 'unist-util-visit' import textr from 'textr' /** * Plugin to improve typography with Textr. * * @type {import('unified').Plugin<[Options?]|void[], Root>} */ export default function remarkTextr(options = {}) { const plugins = options.plugins || [] const promise = Promise.all( plugins.map( /** * @returns {Promise<TextrPlugin>} */ // Default is an `any`. // type-coverage:ignore-next-line async (fn) => (typeof fn === 'string' ? (await import(fn)).default : fn) ) ).then((list) => textr(options.options || {}).use(...list)) return async (tree) => { const typography = await promise visit(tree, 'text', (node) => { node.value = typography.exec(node.value) }) } } <file_sep># remark-textr [![Build][build-badge]][build] [![Coverage][coverage-badge]][coverage] [![Downloads][downloads-badge]][downloads] [![Size][size-badge]][size] [![Sponsors][sponsors-badge]][collective] [![Backers][backers-badge]][collective] [![Chat][chat-badge]][chat] **[remark][]** plugin to [improve typography][typewriter-habits] with [**Textr**][textr]. ## Contents * [What is this?](#what-is-this) * [When should I use this?](#when-should-i-use-this) * [Install](#install) * [Use](#use) * [API](#api) * [`unified().use(remarkTextr[, options])`](#unifieduseremarktextr-options) * [Types](#types) * [Compatibility](#compatibility) * [Security](#security) * [Contribute](#contribute) * [License](#license) ## What is this? This package is a [unified][] ([remark][]) plugin to support [Textr][]. **unified** is a project that transforms content with abstract syntax trees (ASTs). **remark** adds support for markdown to unified. **mdast** is the markdown AST that remark uses. This is a remark plugin that transforms mdast with Textr. ## When should I use this? This project is useful if you want to automatically improve the text in your markdown documents. [Textr][] is a simple way to do that: no need to worry about ASTs. On the other hand, ASTs are powerful, so some things are better done with custom plugins: see [Create a plugin][create-a-plugin]. ## Install This package is [ESM only](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c). In Node.js (version 12.20+, 14.14+, or 16.0+), install with [npm][]: ```sh npm install remark-textr ``` In Deno with [`esm.sh`][esmsh]: ```js import remarkTextr from 'https://esm.sh/remark-textr@5' ``` In browsers with [`esm.sh`][esmsh]: ```html <script type="module"> import remarkTextr from 'https://esm.sh/remark-textr@5?bundle' </script> ``` ## Use Say we have the following file, `example.md`: ````markdown ## spread operator... ```js function(...args) { return args; } ``` ```` And our module `example.js` looks as follows: ```js import {read} from 'to-vfile' import {remark} from 'remark' import remarkTextr from 'remark-textr' main() async function main() { const file = await remark() .use(remarkTextr, {plugins: [ellipses]}) .process(await read('example.md')) console.log(String(file)) } /** * Textr plugin: a function that replaces triple dots with ellipses. * * @type {import('remark-textr').TextrPlugin} */ function ellipses(input) { return input.replace(/\.{3}/gim, '…') } ``` Yields: ````markdown ## spread operator… ```js function(...args) { return args; } ``` ```` ## API This package exports no identifiers. The default export is `remarkTextr`. ### `unified().use(remarkTextr[, options])` Plugin to [improve typography][typewriter-habits] with [**Textr**][textr]. ##### `options` Configuration. ###### `options.plugins` List of [Textr][] plugins (`Array.<string|Function>?`). If strings are passed in, those are loaded with `import`. Textr plugins are available on npm labelled with a [`textr`][textr-plugins] keyword. You can also create them yourself, as shown in the example above. ###### `options.options` [Textr][] options (`Object?`). For example, you may want to set the [ISO 639-1][iso] [locale code][locale] of the content, which is important for stuff like the correct primary and secondary quotes. ## Types This package is fully typed with [TypeScript][]. It exports `Options` and `TextrPlugin` types, which specify the interface of the accepted options and Textr plugins. ## Compatibility Projects maintained by the unified collective are compatible with all maintained versions of Node.js. As of now, that is Node.js 12.20+, 14.14+, and 16.0+. Our projects sometimes work with older versions, but this is not guaranteed. This plugin works with `unified` version 6+ and `remark` version 7+. ## Security Use of `remark-textr` does not involve [**rehype**][rehype] ([**hast**][hast]) or user content so there are no openings for [cross-site scripting (XSS)][xss] attacks. [Textr][] operates on text nodes, which are always escaped by remark. ## Contribute See [`contributing.md`][contributing] in [`remarkjs/.github`][health] for ways to get started. See [`support.md`][support] for ways to get help. This project has a [code of conduct][coc]. By interacting with this repository, organization, or community you agree to abide by its terms. ## License [MIT][license] © [<NAME>][author] <!-- Definitions --> [build-badge]: https://github.com/remarkjs/remark-textr/workflows/main/badge.svg [build]: https://github.com/remarkjs/remark-textr/actions [coverage-badge]: https://img.shields.io/codecov/c/github/remarkjs/remark-textr.svg [coverage]: https://codecov.io/github/remarkjs/remark-textr [downloads-badge]: https://img.shields.io/npm/dm/remark-textr.svg [downloads]: https://www.npmjs.com/package/remark-textr [size-badge]: https://img.shields.io/bundlephobia/minzip/remark-textr.svg [size]: https://bundlephobia.com/result?p=remark-textr [sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg [backers-badge]: https://opencollective.com/unified/backers/badge.svg [collective]: https://opencollective.com/unified [chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg [chat]: https://github.com/remarkjs/remark/discussions [npm]: https://docs.npmjs.com/cli/install [esmsh]: https://esm.sh [health]: https://github.com/remarkjs/.github [contributing]: https://github.com/remarkjs/.github/blob/HEAD/contributing.md [support]: https://github.com/remarkjs/.github/blob/HEAD/support.md [coc]: https://github.com/remarkjs/.github/blob/HEAD/code-of-conduct.md [license]: license [author]: https://denysdovhan.com [remark]: https://github.com/remarkjs/remark [unified]: https://github.com/unifiedjs/unified [textr]: https://github.com/A/textr [textr-plugins]: https://www.npmjs.com/browse/keyword/textr [locale]: https://github.com/A/textr#locale-option-consistence [iso]: https://www.wikiwand.com/en/List_of_ISO_639-1_codes [typewriter-habits]: https://practicaltypography.com/typewriter-habits.html [xss]: https://en.wikipedia.org/wiki/Cross-site_scripting [typescript]: https://www.typescriptlang.org [rehype]: https://github.com/rehypejs/rehype [hast]: https://github.com/syntax-tree/hast [create-a-plugin]: https://unifiedjs.com/learn/guide/create-a-plugin/
ccdb090259facd85dbc1150d545a2ae6eba823f2
[ "JavaScript", "Markdown" ]
2
JavaScript
remarkjs/remark-textr
96ed5d0df9bee62fa7744b3d6c10a61ee85c1bfd
fd1feb266bf90d16be7169bdb1261947dd92c17f
refs/heads/master
<file_sep>document.addEventListener("DOMContentLoaded",()=>{ const items = ["reviewed","blacklist"]; for(const item of items){ const $item = $(`.${item}`); $item.click(e=>{ const target = $(e.target); const url = target.attr("data-url"); const oppValue = target.text() === "true" ? 0 : 1; fetch(`${url}?_method=PUT&${item}=${oppValue}`,{ method:"POST" }).then(res=>{ if(res.status===200){ const oppTextValue = !!oppValue ? "true" : "false"; target.text(oppTextValue); }else{ target.text("💀Error💀"); } }) }) } })<file_sep>var fetch = require("node-fetch"); const { JSDOM } = require("jsdom"); const INJECTED_FORM_ACTION = "/shelters/?/formUrl"; class ShelterFormHandler{ constructor(URL,shelterApiId){ this.URL = URL; this.shelterApiId = shelterApiId; // Used to "Submit" form to update shelter form elements in DB const re = /\?/; this.formActionUrl = INJECTED_FORM_ACTION.replace(re,this.shelterApiId); } async getCleanPage(){ const html = await new Promise((res,rej)=>{ fetch(this.URL) .then(response=>response.text()) .then(html=>res(html)) .catch(err=>rej(err)) }) this.dom = this.getSterilizedHTML(html); const form = this.dom.window.document.querySelector("form"); const input = Array.from(form.querySelectorAll("input")).map(input=>{ return {"name":input.name,"type":input.type} }); const select = Array.from(form.querySelectorAll("select")).map(select=>{ return {"name":select.name,"options":Array.from(select.querySelectorAll("option")).map(option=>{ return {"text":option.textContent, "value": option.value} })} }); const textarea = Array.from(form.querySelectorAll("textarea")).map(textarea=>textarea.name); return { html:this.dom.serialize(), formData:{ input : input, select : select, textarea : textarea } }; } // Resolves issue where original form has attached event handlers. getSterilizedHTML(html){ const dom = new JSDOM(html,{ includeNodeLocations: true }); const old_form = dom.window.document.querySelector("form"); const new_form = dom.window.document.createElement("form"); while (old_form.childNodes.length > 0) { const child = old_form.childNodes[0]; new_form.appendChild(child); } old_form.parentNode.replaceChild(new_form, old_form); new_form.action = this.formActionUrl; new_form.method = "POST"; return dom; } } module.exports = ShelterFormHandler;<file_sep>const express = require('express'); const router = express.Router(); const authenticationHandler = (req, res, next) => { if (req.isAuthenticated()){ return next(); } res.redirect('/'); } const admingAuthentication = (req,res,next) => { if(req.user && req.user.admin === 1){ next(); }else{ res.redirect("/logout"); } } /** * Properly handles errors sent via session. */ const errorHandler = (req,res,next) => { if(req.session.msg){ res.locals.msg = req.session.msg; req.session.msg = null; } next(); } const injectUser = (req,res,next) => { if(req.user){ res.locals.user = req.user; } next(); } module.exports = (dbHandler) => { // Injecting data router.use(errorHandler); router.use(injectUser); const indexRouter = require('./index')(dbHandler,authenticationHandler); router.use('/', indexRouter); const sheltersRouter = require('./shelters')(dbHandler, admingAuthentication); router.use('/shelters', sheltersRouter); // Authenticated after this point router.use(authenticationHandler); const metaFormRouter = require('./metaForm')(dbHandler); router.use('/metaForm', metaFormRouter); // Authenticated Admin after this point router.use(admingAuthentication); // admin const adminRouter = require('./admin')(dbHandler); router.use('/admin', adminRouter); return router; }<file_sep>#To Do List - Set up Admin functionality to assess shelters and update accordingly - Set up user metaform completion (partial completion, too) - Complete user shelter form auto-fill ## Nice to haves - Save erroneous data from sign up/log in attempts - nav items properly active on route<file_sep>var fs = require('fs'); var dbFile = './.data/petApp.db'; module.exports = new class DbHandler { constructor() { if(!fs.existsSync(dbFile)){ this.db = require("./db"); this.createTables(); }else{ this.db = require("./db"); } } createTables() { this.db.run("CREATE TABLE 'users' ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `username` TEXT NOT NULL UNIQUE, `password` TEXT NOT NULL, `email` TEXT, `admin` INTEGER DEFAULT 0);"); this.db.run("CREATE TABLE `shelters` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `api_id` TEXT UNIQUE, `reviewed` INTEGER DEFAULT 0, `blacklist` INTEGER DEFAULT 0, `user_id` INTEGER, `formUrl` TEXT, `actionUrl` TEXT);"); this.db.run("CREATE TABLE `shelterFormInputs` ( `shelter_id` INTEGER NOT NULL, `name` TEXT, `type` TEXT, `element` TEXT, `options` TEXT,`meta_answer_id` INTEGER);"); this.db.run("CREATE TABLE `metaAnswers` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `common_name` TEXT NOT NULL, `description` TEXT);"); this.db.run("CREATE TABLE `userMetaAnswers` ( `user_id` INTEGER NOT NULL, `meta_answer_id` INTEGER, `value` BLOB);"); } findUserByUsername(username){ return new Promise((res, rej)=>{ const sql = "SELECT * FROM users WHERE username=?;"; this.db.get(sql,username,(err,row)=>{ if(err) return rej(err); res(row); }) }) } findUserById(id){ return new Promise((res, rej)=>{ const sql = "SELECT * FROM users WHERE id=?;"; this.db.get(sql,id,(err,row)=>{ if(err) return rej(err); res(row); }) }) } insertNewUser({username,email, password}){ const self = this; return new Promise((res, rej)=>{ const sql = "INSERT INTO users (username, email, password) VALUES (?,?,?)"; this.db.run(sql, [username,email, password], function(err){ if(err) rej(err); self.findUserById(this.lastID) .then(user=>res(user)) .catch(err=>rej(err)) }); }); } requestShelterReview(api_id, user_id){ return new Promise((res,rej)=>{ const sql="INSERT INTO shelters (api_id, user_id) VALUES (?,?);"; this.db.run(sql,[api_id,user_id],(err)=>{ if(err) return rej(err); res(); }) }) } getShelterByApiId(api_id){ return new Promise((res,rej)=>{ const sql="SELECT * FROM shelters WHERE api_id=?"; const sql_for_formInputs = "SELECT * FROM shelterFormInputs LEFT JOIN metaAnswers ON shelterFormInputs.meta_answer_id=metaAnswers.id WHERE shelter_id=?"; const sql_for_metaAnswers = "SELECT * FROM metaAnswers"; this.db.get(sql,api_id,function(err,row){ if(err) return rej(err); if(!row) return res(row); this.db.all(sql_for_formInputs, api_id, function(err2,rows){ if(err2) return rej(err2); this.db.all(sql_for_metaAnswers,(err3,rows2)=>{ if(err3) return rej(err3); res({ shelter: row, formInputs: rows, metaAnswers: rows2 }) }) }.bind(this)) }.bind(this)) }) } getShelters(){ return new Promise((res,rej)=>{ const sql="SELECT * FROM shelters"; this.db.all(sql,(err,rows)=>{ if(err) return rej(err); res(rows); }) }) } updateShelter(shelter_id,sqlParams){ let sql="UPDATE shelters SET"; const _sqlParams = []; const keys = Object.keys(sqlParams); for(const key of keys){ sql += ` ${key}=?`; _sqlParams.push(sqlParams[key]); } sql += " WHERE api_id=?"; _sqlParams.push(shelter_id); return new Promise((res,rej)=>{ this.db.run(sql,_sqlParams,function(err){ if(err) return rej(err); res(this.changes>0); }) }) } insertShelterFormInput(shelter_id, element, type=null, name, options=null){ return new Promise((res,rej)=>{ const sql = 'INSERT INTO shelterFormInputs (shelter_id, element, type, name, options) VALUES (?,?,?,?,?);'; this.db.run(sql, [shelter_id, element, type, name, options], function(err){ if(err) return rej(err); res(); }) }); } shelterFormInputsExists(shelter_id){ return new Promise((res,rej)=>{ const sql = 'SELECT * FROM shelterFormInputs WHERE shelter_id=?'; this.db.get(sql, shelter_id, function(err,row){ if(err) return rej(err); res(row); }) }); } }<file_sep>require('dotenv').load(); // required for using .env file const db = require("../db"); const _ = require("../controllers/shelterController"); _.mountDb(db);<file_sep>const express = require('express'); const router = express.Router(); const verifyAdmin = user =>{ return user.admin === 1; } module.exports = dbHandler => { router.get('/',(req,res)=>{ dbHandler.getShelters() .then(shelters=>{ res.locals.shelters = shelters; res.render("admin_index",{title: "Admin"}); }) }); return router; }
304e3c466e92435510fb066fba57969ac95a6b8e
[ "JavaScript", "Markdown" ]
7
JavaScript
Shaddyjr/ankitasPetApp
72d024f90969896d1d7c3962a68e99a58665979a
57a6281fb14a1182215774d453ea9c514a0b8011
refs/heads/master
<file_sep>package neurotech.com.br.wantit.model; import java.util.List; public class Device { private String deviceId; private String deviceName; private List<App> listApp; public Device(String deviceId, String deviceName, List<App> listApp) { super(); this.deviceId = deviceId; this.deviceName = deviceName; this.listApp = listApp; } public Device() { super(); } public String getDeviceId() { return deviceId; } public void setDeviceId(String deviceId) { this.deviceId = deviceId; } public String getDeviceName() { return deviceName; } public void setDeviceName(String deviceName) { this.deviceName = deviceName; } public List<App> getListApp() { return listApp; } public void setListApp(List<App> listApp) { this.listApp = listApp; } @Override public String toString() { return "Device [deviceId=" + deviceId + ", deviceName=" + deviceName + "]"; } } <file_sep>package neurotech.com.br.wantit.model; public class App { private String name; private String bundleId; private String category; private String price; public App() { super(); } public App(String name, String packageName, String category, String price) { super(); this.name = name; this.bundleId = packageName; this.category = category; this.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPackageName() { return bundleId; } public void setPackageName(String packageName) { this.bundleId = packageName; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } } <file_sep>package neurotech.com.br.wantit.model; import java.util.ArrayList; /** * Created by JoaoCalixto on 24/10/2015. */ public class Request { public ArrayList<String> taglist; public String acao; public String deviceid; } <file_sep>package neurotech.com.br.wantit.util; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Created by JoaoCalixto on 24/10/2015. */ public class LocaisUtil { // private static final String MINT = "FC:5A:29:87:82:DF"; // private static final String blueberry = "EA:7A:88:67:FE:40"; // private static final String ice = "E1:56:9B:61:8E:CB"; HashMap<String, String> locaisEnderecos = new HashMap<String,String>(); public LocaisUtil(){ locaisEnderecos.put("JUMP BRASIL","R. Cap. Lima"); locaisEnderecos.put("WANT.IT","EA:7A:88:67:FE:40"); locaisEnderecos.put("LOJA ICE","E1:56:9B:61:8E:CB"); locaisEnderecos.put("LOJA MINT","FC:5A:29:87:82:DF"); } public String getPlace(String placeAddres){ String[] split = placeAddres.split(","); Set<Map.Entry<String, String>> entries = locaisEnderecos.entrySet(); for (Map.Entry<String, String> entry : locaisEnderecos.entrySet()){ String add = entry.getValue(); if(add.contains(split[0])){ return entry.getKey(); } } return locaisEnderecos.get(placeAddres); } }
ee4dc8f3c43a48c4a935b66bb7a9616534822ea4
[ "Java" ]
4
Java
joaocalixto/Wantit
74566e4fcb736aa5ad43f9009e44bd58d3942980
1a0eebe63f830d5582a0e933aa91ee2b6e65054f
refs/heads/master
<repo_name>johndearman/gtms<file_sep>/api/tickets.php <?php require_once("../classes/class.database.php"); $db = new Database(); $db->query(" SELECT ar_id, ar_number, action_type_description, groups.group_description, status.status_description, high_level_outage, low_level_outage, users.username, quickets.quicket_description, classifications.classification_description, ar_delete, description FROM meta_action_requests AS ar LEFT JOIN action_types ON ar.action_type_id = action_types.action_type_id LEFT JOIN groups ON ar.group_id LEFT JOIN status ON ar.status_id LEFT JOIN users ON ar.submitter_id = users.user_id LEFT JOIN quickets ON ar.quicket_id = quickets.quicket_id LEFT JOIN classifications ON ar.classification_id = classifications.classification_id "); $action_requests = $db->single(); $db->query(" SELECT action_info_id, ar_id, action_descriptions.action_description, communities.community_description, op_impact_description, zulu_date_time_out, zulu_date_time_in, outage_duration, request_source.source_description AS request_source, zulu_monitor_status_start, zulu_monitor_status_stop, zulu_date_time_etr, validation_source.source_id, validation_source.source_description AS validation_source, element_types.element_type_description, validated, hit_si, platforms.platform_description, action_types.action_type_description, priorities.priority_description, service1.service_description AS svc1, service2.service_description AS svc2, service3.service_description AS svc3, submitter_site.site_description AS submitter_site, support_site1.site_description AS support_site1, support_site2.site_description AS support_site2, groups.group_description, users.username, on_call_pool FROM meta_action_info AS ai LEFT JOIN action_descriptions ON ai.action_description_id = action_descriptions.action_description_id LEFT JOIN communities ON ai.impacted_community_id = communities.community_id LEFT JOIN sources AS request_source ON ai.request_source_id = request_source.source_id LEFT JOIN sources AS validation_source ON ai.validation_source_id = validation_source.source_id LEFT JOIN element_types ON ai.element_type_id = element_types.element_type_id LEFT JOIN platforms ON ai.platform_domain_id = platforms.platform_id LEFT JOIN action_types ON ai.action_type_id = action_types.action_type_id LEFT JOIN priorities ON ai.priority_id = priorities.priority_id LEFT JOIN services AS service1 ON ai.service1_id = service1.service_id LEFT JOIN services AS service2 ON ai.service2_id = service2.service_id LEFT JOIN services AS service3 ON ai.service3_id = service3.service_id LEFT JOIN sites AS submitter_site ON ai.submitter_site_id = submitter_site.site_id LEFT JOIN sites AS support_site1 ON ai.supporting_site1_id = support_site1.site_id LEFT JOIN sites AS support_site2 ON ai.supporting_site2_id = support_site2.site_id LEFT JOIN groups ON ai.assigned_group_id = groups.group_id LEFT JOIN users ON ai.assigned_technician_id = users.user_id WHERE ar_id = 1; "); $action_items = $db->single(); $db->query(" SELECT fault_id, ar_id, fault_date_time_out, fault_date_time_in, services.service_description, fault_duration, sites.site_description AS fault_location, fault_categories.fault_category_description, rfo1.rfo_description AS rfo1, rfo2.rfo_description, vendors.vendor_description, vendor_ticket_number, rfo_remarks FROM meta_fault_summary AS fs LEFT JOIN services ON fs.service4_id = services.service_id LEFT JOIN sites ON fs.fault_location_id = sites.site_id LEFT JOIN fault_categories ON fs.fault_category_id = fault_categories.fault_category_id LEFT JOIN rfo as rfo1 ON fs.rfo1_id = rfo1.rfo_id LEFT JOIN rfo AS rfo2 ON fs.rfo2_id = rfo2.rfo_id LEFT JOIN vendors ON fs.vendor_id = vendors.vendor_id "); $fault_summary = $db->single(); echo "<pre>\n"; print_r($action_requests); print_r($action_items); print_r($fault_summary); echo "</pre>\n"; //print_r(json_encode($results)); ?><file_sep>/new_ticket.php <!doctype html> <?php require_once("template_engine.php"); ?> <html lang="en"> <head> <meta charset="utf-8"> <title>Global Trouble Management System</title> <script src="js/external/jquery/jquery.js"></script> <script src="js/jquery-ui.js"></script> <script src="js/flexgrid/js/flexigrid.js"></script> <!--<script src="js/flexgrid/js/flexigrid.pack.js"></script>--> <script src="js/new_ticket.js"></script> <link rel="stylesheet" href="js/jquery-ui.css"> <link rel="stylesheet" href="js/flexgrid/css/flexigrid.css"> <link rel="stylesheet" href="css/styles.css"> </head> <body> <div id="main_container"> <div id="details_container" class="ui-widget-content"> <div id="details_header"> New Action Request <input type="button" id="update_ticket" value="Save" /> </div> <div id="status_container"> <div class="box1"> <i>AR Number</i><br /> <input id="ar_number" type="text" value="" disabled=true /> </div> <div id="status" class="box1"> Status<br /> <?php echo getDropDown("status"); ?> </div> <div id="higher_level_outage" class="box1"> Higher Level Outage<br /> <input id="high_level_outage" type="text" value="" /> </div> <div class="box1"> Lower Level Outage<br /> <input id="low_level_outage" type="text" value="" size="1" /> </div> <div class="box1"> <strong>Submitter</strong><br /> <?php echo getDropDown("users", "", "submitter_id"); ?> </div> <div class="box1"> Quicket Type<br /> <?php echo getDropDown("quicket"); ?> </div> <div class="box1"> Record Classification<br /> <?php echo getDropDown("classification"); ?> </div> </div> <div id="action_tab_container" class="tab_container"> <ul> <li><a href="#contact_info">Contact Info</a></li> <li><a href="#action_info">Action Info</a></li> </ul> <div id="contact_info">Contact Information</div> <div id="action_info"> <div id="action_description_container"> <span class="required_input">Action Description</span><br /> <textarea id="action_description_text"></textarea> <br /> <span class="not_required_input">Status or Resolution Summary</span><br /> <textarea id="resolution_text"></textarea> </div> <div id="impacted_container"> <div class="required_input inline_block"> Impact Communities<br /> <?php echo getDropDown("community"); ?> </div> <div class="required_input inline_block"> Operational Impact Description<br /> <input id="op_impact" type="text" value="" /> </div> <br /> <div class="inline_block"> Zulu Date Time Out<br /> <input id="zulu_date_time_out" type="text" value="" disabled="true" /> </div> <div class="inline_block"> Zulu Date Time In<br /> <input id="zulu_date_time_in" type="text" value="" disabled="true" /> </div> <div class="inline_block"> Outage Duration Hours<br /> <input id="outage_duration" type="text" value="" disabled="true" /> </div> <div class="inline_block"> Request Source<br /> <?php echo getDropDown("source", "request"); ?> </div> <br /> <div class="inline_block"> Zulu Monitor Status Start +<br /> <input id="zulu_monitor_status_start" type="text" value="" /> </div> <div class="inline_block"> Zulu Monitor Status Stop +<br /> <input id="zulu_monitor_status_stop" type="text" value="" /> </div> <div class="inline_block"> Zulu Date Time ETR +<br /> <input id="zulu_date_time_etr" type="text" value="" /> </div> </div> <div id="validation_container"> <div class="inline_block"> Validation Source<br /> <?php echo getDropDown("source", "validation"); ?> </div> <div class="inline_block"> Element ID Type<br /> <?php echo getDropDown("element_type"); ?> </div> <div class="inline_block"> Element ID +<br /> <input id="element_id" type="text" value="" /> </div> <div class="inline_block"> Validated<br /> <input id="validated" type="text" value="" disabled="true" size="1" /> </div> <div class="inline_block"> HIT or SI<br /> <input id="hit_si" type="text" value="" disabled="true" size="1" /> </div> <div class="inline_block"> Replace Subform<br /> <select id="replace_subform"> <option value="" selected>&nbsp;</option> <option value="no">No</option> <option value="yes">Yes</option> </select> </div> <div class="inline_block"> Platform or Domain<br /> <?php echo getDropDown("platform", "domain"); ?> </div> <br /> <div class="required_input inline_block"> Action Type<br /> <?php echo getDropDown("action_type"); ?> </div> <div class="required_input inline_block"> Assigned Priority<br /> <?php echo getDropDown("priority"); ?> </div> <div class="required_input inline_block"> Service 1<br /> <?php echo getDropDown("service", "", "service1"); ?> </div> <div class="required_input inline_block"> Service 2<br /> <?php echo getDropDown("service", "", "service2"); ?> </div> <div class="required_input inline_block"> Service 3<br /> <?php echo getDropDown("service", "", "service3"); ?> </div> <br /> <div class="required_input inline_block"> Submitter Site<br /> <?php echo getDropDown("site", "submitter", "submitter_site"); ?> </div> <div class="required_input inline_block"> Supporting Site 1<br /> <?php echo getDropDown("site", "", "supporting_site1"); ?> </div> <div class="required_input inline_block"> Supporting Site 2<br /> <?php echo getDropDown("site", "", "supporting_site2"); ?> </div> <div class="required_input inline_block"> Assigned Group<br /> <?php echo getDropDown("assigned_group"); ?> </div> <div class="required_input inline_block"> Assigned Technician<br /> <?php echo getDropDown("users", "", "assigned_technician"); ?> </div> <div class="required_input inline_block"> On Call Pool<br /> <input type="text" value="" disabled="true" /> </div> </div> </div> </div> </div> <div id="details_tab_container" class="tab_container"> <ul> <li><a href="#fault_summary">Fault Summary</a></li> <li><a href="#reporting">Reporting</a></li> <li><a href="#tms_knowledgebase">TMS Knowledgebase</a></li> <li><a href="#comm">COMM</a></li> <li><a href="#dms">DMS</a></li> <li><a href="#hardware">Hardware</a></li> <li><a href="#software">Software</a></li> <li><a href="#cert">CERT</a></li> <li><a href="#work_order">Work Order</a></li> <li><a href="#subform">Subform</a></li> <li><a href="#history">History</a></li> </ul> <div id="fault_summary"> <div id="fault_container"> <div class="required_input inline_block"> Zulu Fault Date Time Out +<br /> <input id="zulu_fault_date_time_out" type="text" width="130px" /> </div> <div class="inline_block"> Zulu Fault Date Time In +<br /> <input id="zulu_fault_date_time_in" type="text" width="130px" /> </div> <div class="inline_block"> Service 4<br /> <?php echo getDropDown("service", "", "service4"); ?> </div> <div class="inline_block"> Fault Duration Hours<br /> <input id="fault_duration" type="text" disabled="true" /> </div> <div class="inline_block"> Location of Problem +<br /> <?php echo getDropDown("site", "", "fault_location_id"); ?> </div> <br /> <div class="inline_block"> Fault Category<br /> <?php echo getDropDown("fault_category"); ?> </div> <div class="inline_block"> RFO 1<br /> <?php echo getDropDown("rfo", "", "rfo1"); ?> </div> <div class="inline_block"> RFO 2<br /> <?php echo getDropDown("rfo", "", "rfo2"); ?> </div> <div class="inline_block"> Vendor<br /> <?php echo getDropDown("vendor"); ?> </div> <div class="inline_block"> Vendor Ticket Number<br /> <input id="vendor_ticket_number" type="text" value="" disabled="true" /> </div> <br /> <div class="inline_block"> RFO Remarks<br /> <input id="rfo_remarks" type="text" value="" style="width:600px" /> </div> </div> </div> <div id="reporting">Reporting</div> <div id="tms_knowledgebase">TMS Knowledgebase</div> <div id="comm">COMM</div> <div id="dms">DMS</div> <div id="hardware">Hardware</div> <div id="software">Software</div> <div id="cert">CERT</div> <div id="work_order">Work Order</div> <div id="subform">Subform</div> <div id="history">History</div> </div> </div> </body> </html><file_sep>/api/fault_grid.php <?php require_once("../classes/class.database.php"); $db = new Database(); $db->query(" SELECT ar_id, fault_date_time_out, fault_date_time_in, service.service_description, fault_duration, site.site_description, fault_category.fault_category_description, rfo1.rfo_description AS rfo1_description, rfo2.rfo_description AS rfo2_description, vendor.vendor_description, vendor_ticket_number, rfo_remarks FROM meta_fault_summary AS fs LEFT JOIN service ON fs.service4_id = service.service_id LEFT JOIN site ON fs.fault_location_id = site.site_id LEFT JOIN fault_category ON fs.fault_category_id = fault_category.fault_category_id LEFT JOIN rfo AS rfo1 ON fs.rfo1_id = rfo1.rfo_id LEFT JOIN rfo AS rfo2 ON fs.rfo2_id = rfo2.rfo_id LEFT JOIN vendor ON fs.vendor_id = vendor.vendor_id "); $rows = $db->resultSet(); // Used to test the size of the grid display, since we don't have enough dummy data // for($i=1; $i<=25; $i++){ // $rows[$i] = $rows[0]; // } $jsonData = array('page'=>1,'total'=>0,'rows'=>array()); foreach($rows AS $rowNum => $row){ //If cell's elements have named keys, they must match column names //Only cell's with named keys and matching columns are order independent. $entry = array('id' => ($rowNum+1), 'cell'=>array( 'ar_id' => $row['ar_id'], //This is temporary to allow for dummy data 'fault_date_time_out' => $row['fault_date_time_out'], 'fault_date_time_in' => $row['fault_date_time_in'], 'service_description' => $row['service_description'], 'fault_duration' => $row['fault_duration'], 'site_description' => $row['site_description'], 'fault_category_description' => $row['fault_category_description'], 'rfo1_description' => $row['rfo1_description'], 'rfo2_description' => $row['rfo2_description'], 'vendor_description' => $row['vendor_description'], 'vendor_ticket_number' => $row['vendor_ticket_number'], 'rfo_remarks' => $row['rfo_remarks'] ) ); $jsonData['rows'][] = $entry; } $jsonData['total'] = count($rows); echo json_encode($jsonData); ?><file_sep>/js/gtms.js $(function() { var selected_ar; var selected_row = 1; var selected_fault; var selected_ar_tab; var selected_fault_tab; var current_ar_data; var current_ai_data; var current_fs_data; $( "#tickets_container" ).resizable({ handles: 's', stop: function(event, ui) { $(this).css("width", ''); } }); $("#action_tab_container").tabs({ active: 1, activate: function() { selected_ar_tab = $("li.ui-tabs-active").children(":first").text(); } }); $("#details_tab_container").tabs({ activate: function() { selected_fault_tab = $("li.ui-tabs-active").children(":first").text(); } }); $(".flex1").flexigrid({ url:"api/ar_grid.php", dataType: "json", colModel: [ {display: "AR ID", name: "ar_id", hide:true}, {display: "AR Number", name: "ar_number", width:100, sortable:true}, {display: "Status", name: "status_description", width:100, sortable:true}, {display: "Group", name: "assigned_group_description", width:200, sortable:true}, {display: "Action Type", name: "action_type_description", width:200, sortable:true}, {display: "Description", name: "description", width:400, sortable:true} ], searchitems: [ {display: "AR Number", name: "ar_number", isdefault: true}, {display: "Status", name: "status_description"}, {display: "Group", name: "assigned_group_description"}, {display: "Action Type", name: "action_type_description"}, {display: "Description", name: "description"} ], sortname: "ar_id", sortorder: "asc", usepager: true, height: 100, useRp: true, rp:100, singleSelect: true, toggleSingleRow: false, onSuccess: function() { $("table.flex1 tr[id^='row']").on("click", function() { if(selected_ar !== $(this).children(":first").text()) { selected_ar = $(this).children(":first").text(); populate_ar_data(); } }); $("tr#row" + selected_row).trigger("click"); } }); /* var fault_grid = $(".flex2").flexigrid({ url:"api/fault_grid.php", dataType: "json", colModel: [ {display: "AR ID", name: "ar_id", hide:true}, {display: "Zulu Date Time Out", name: "fault_date_time_out", width:100}, {display: "Zulu Date Time In", name: "fault_date_time_in", width:100}, {display: "Service 4", name: "service_description", width:100}, {display: "Fault Duration", name: "fault_duration", width:70}, {display: "Location of Problem", name: "site_description", width:100}, {display: "Fault Category", name: "fault_category_description", width:75}, {display: "RFO 1", name: "rfo1_description", width:50}, {display: "RFO 2", name: "rfo2_description", width:50}, {display: "Vendor", name: "vendor_description", width:50}, {display: "Vendor Ticket", name: "vendor_ticket_number", width:70}, {display: "RFO Remarks", name: "rfo_remarks", width:130} ], sortorder: "asc", height: 100, singleSelect: true, onSuccess: function(data) { $("table.flex2 tr[id^='row']").on("click", function(data) { selected_fault = $(this).children(":first").text(); }); } }); */ function populate_ar_data() { $.getJSON("api/action_requests.php?ar_id=" + selected_ar, function(response){ current_ar_data = response; $("input#ar_number").val(response[0].ar_number); $("select#status option").each(function(){ if($(this).val()==response[0].status_id || !response[0].status_id) { $(this).attr("selected", "selected"); return false; } }); $("input#high_level_outage").val(response[0].high_level_outage); $("input#low_level_outage").val(response[0].low_level_outage); $("input#submitter").val(response[0].username); $("select#quicket option").each(function(){ if($(this).val() == response[0].quicket_id || !response[0].quicket_id) { $(this).attr("selected", "selected"); return false; } }); $("select#classification option").each(function(){ if($(this).val() == response[0].classification_id || !response[0].classification_id) { $(this).attr("selected", "selected"); return false; } }); selected_delete = response[0].ar_delete == 0 ? "no" : "yes"; $("select#delete option").each(function(){ if($(this).val()==selected_delete) $(this).attr("selected", "selected"); }); }); //This needs to not be called procedurally from this function populate_action_info_tab(); populate_fault_tab(); } function populate_action_info_tab() { $.getJSON("api/action_info.php?ar_id=" + selected_ar, function(response){ current_ai_data = response; $("textarea#action_description_text").val(response[0].action_description); $("textarea#resolution_text").val(response[0].resolution_summary); $("select#community option").each(function(){ if($(this).val()==response[0].community_id) $(this).attr("selected", "selected"); }); //$("input#op_impact").val(response[0].op_impact_description); $("input#zulu_date_time_out").val(response[0].zulu_date_time_out); $("input#zulu_date_time_in").val(response[0].zulu_date_time_in); $("input#outage_duration").val(response[0].outage_duration); $("select#request_source option").each(function(){ if($(this).val()==response[0].request_source_id) $(this).attr("selected", "selected"); }); $("input#zulu_monitor_status_start").val(response[0].zulu_monitor_status_start); $("input#zulu_monitor_status_stop").val(response[0].zulu_monitor_status_stop); $("input#zulu_date_time_etr").val(response[0].zulu_date_time_etr); $("select#validation_source option").each(function(){ if($(this).val()==response[0].validation_source_id) $(this).attr("selected", "selected"); }); $("select#element_type option").each(function(){ if($(this).val()==response[0].element_type_id) $(this).attr("selected", "selected"); }); $("input#element_id").val(response[0].element_id); $("input#validated").val(response[0].validated); $("input#hit_si").val(response[0].hit_si); $("select#domain_platform option").each(function(){ if($(this).val()==response[0].platform_domain_id) $(this).attr("selected", "selected"); }); $("select#action_type option").each(function(){ if($(this).val()==response[0].action_type_id) $(this).attr("selected", "selected"); }); $("select#priority option").each(function(){ if($(this).val()==response[0].priority_id) $(this).attr("selected", "selected"); }); $("select#service1 option").each(function(){ if($(this).val()==response[0].service1_id) $(this).attr("selected", "selected"); }); $("select#service2 option").each(function(){ if($(this).val()==response[0].service2_id) $(this).attr("selected", "selected"); }); $("select#service3 option").each(function(){ if($(this).val()==response[0].service2_id) $(this).attr("selected", "selected"); }); $("select#submitter_site option").each(function(){ if($(this).val()==response[0].submitter_site_id) $(this).attr("selected", "selected"); }); $("select#supporting_site1 option").each(function(){ if($(this).val()==response[0].supporting_site1_id) $(this).attr("selected", "selected"); }); $("select#supporting_site2 option").each(function(){ if($(this).val()==response[0].supporting_site2_id) $(this).attr("selected", "selected"); }); $("select#assigned_group option").each(function(){ if($(this).val()==response[0].assigned_group_id) $(this).attr("selected", "selected"); }); $("select#assigned_technician option").each(function(){ if($(this).val()==response[0].assigned_technician) $(this).attr("selected", "selected"); }); }); } function populate_fault_tab() { $.getJSON("api/fault_summary.php?ar_id=" + selected_ar, function(response){ current_fs_data = response; $("input#zulu_fault_date_time_out").val(response[0].fault_date_time_out); $("input#zulu_fault_date_time_in").val(response[0].fault_date_time_in); $("select#service4 option").each(function(){ if($(this).val()==response[0].service4_id) $(this).attr("selected", "selected"); }); $("input#fault_duration").val(response[0].fault_duration); $("select#fault_location_id option").each(function(){ if($(this).val()==response[0].fault_location_id) $(this).attr("selected", "selected"); }); $("select#fault_category option").each(function(){ if($(this).val()==response[0].fault_category_id) $(this).attr("selected", "selected"); }); $("select#rfo1 option").each(function(){ if($(this).val()==response[0].rfo1_id) $(this).attr("selected", "selected"); }); $("select#rfo2 option").each(function(){ if($(this).val()==response[0].rfo2_id) $(this).attr("selected", "selected"); }); $("select#vendor option").each(function(){ if($(this).val()==response[0].vendor_id) $(this).attr("selected", "selected"); }); $("input#vendor_ticket_number").val(response[0].vendor_ticket_number); $("input#rfo_remarks").val(response[0].rfo_remarks); }); } $("#update_ticket").on("click", function updateTicket() { var ar = new Object(); ar.ar_id = selected_ar; ar.status_id = $("select#status option:selected").val(); ar.high_level_outage = $("input#high_level_outage").val(); ar.quicket_id = $("select#quicket option:selected").val(); ar.classification_id = $("select#classification option:selected").val(); ar.action_type_id = $("select#action_type option:selected").val(); ar.description = $("textarea#action_description_text").val(); ar.assigned_group_id = $("select#assigned_group option:selected").val(); update_action_request(ar); var action_info = new Object(); action_info.ar_id = selected_ar; action_info.action_description = $("textarea#action_description_text").val(); action_info.resolution_summary = $("textarea#resolution_text").val(); action_info.community_id = $("select#community option:selected").val(); action_info.op_impact_description = $("input#op_impact").val(); action_info.request_source_id = $("select#request_source option:selected").val(); action_info.zulu_monitor_status_start = $("input#zulu_monitor_status_start").val(); action_info.zulu_monitor_status_stop = $("input#zulu_monitor_status_stop").val(); action_info.zulu_date_time_etr = $("input#zulu_date_time_etr").val(); action_info.validation_source_id = $("select#validation_source option:selected").val(); action_info.element_type_id = $("select#element_type option:selected").val(); action_info.element_id = $("input#element_id").val(); action_info.platform_domain_id = $("select#domain_platform option:selected").val(); action_info.action_type_id = $("select#action_type option:selected").val(); action_info.priority_id = $("select#priority option:selected").val(); action_info.service1_id = $("select#service1 option:selected").val(); action_info.service2_id = $("select#service2 option:selected").val(); action_info.service3_id = $("select#service3 option:selected").val(); action_info.submitter_site_id = $("select#submitter_site option:selected").val(); action_info.supporting_site1_id = $("select#supporting_site1 option:selected").val(); action_info.supporting_site2_id = $("select#supporting_site2 option:selected").val(); action_info.assigned_group_id = $("select#assigned_group option:selected").val(); action_info.assigned_technician_id = $("select#assigned_technician option:selected").val(); update_action_info(action_info); var fault = new Object(); fault.ar_id = selected_ar; fault.fault_date_time_out = $("input#fault_date_time_out").val(); fault.zulu_date_time_id = $("input#fault_date_time_in").val(); fault.service4_id = $("select#service4 option:selected").val(); fault.fault_location_id = $("select#fault_location_id option:selected").val(); fault.fault_category_id = $("select#fault_category option:selected").val(); fault.rfo1_id = $("select#rfo1 option:selected").val(); fault.rfo2_id = $("select#rfo2 option:selected").val(); fault.vendor_id = $("select#vendor option:selected").val(); fault.vendor_ticket_number = $("input#vendor_ticket_number").val(); fault.rfo_remarks = $("input#rfo_remarks").val(); update_fault_summary(fault); }); // Eventually this functions should only receive modified data, but currently only get all data from fields // these update functions will pass single variables (e.g., ar_id = 1, ar_number: xxx), this will allow // for only updating new data, and not assuming ALL fields have been passed to the API function update_action_request(ar) { $.ajax({ type: "POST", url: "api/update_action_request.php", data: ar, dataType: JSON }); } function update_action_info(action_info) { $.ajax({ type: "POST", url: "api/update_action_info.php", data: action_info, dataType: JSON }); } function update_fault_summary(fault) { $.ajax({ type: "POST", url: "api/update_fault_summary.php", data: fault, dataType: JSON }).complete(function(response) { selected_row = $('table.flex1 .trSelected').attr("id").slice(-1); $('.flex1').flexReload(); $('.flex2').flexReload(); }); } }); <file_sep>/gtms.sql -- phpMyAdmin SQL Dump -- version 4.1.12 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: Sep 04, 2014 at 09:33 AM -- Server version: 5.6.16 -- PHP Version: 5.5.11 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!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 */; /*!40101 SET NAMES utf8 */; -- -- Database: `gtms` -- CREATE DATABASE IF NOT EXISTS `gtms` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci; USE `gtms`; -- -------------------------------------------------------- -- -- Table structure for table `action_descriptions` -- CREATE TABLE IF NOT EXISTS `action_descriptions` ( `action_description_id` int(11) NOT NULL AUTO_INCREMENT, `action_description` text NOT NULL, PRIMARY KEY (`action_description_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ; -- -- Dumping data for table `action_descriptions` -- INSERT INTO `action_descriptions` (`action_description_id`, `action_description`) VALUES (1, 'TEST TICKET TO SCOTT SERVER'), (2, 'Action Description 2'), (3, 'Action Description 3'); -- -------------------------------------------------------- -- -- Table structure for table `action_type` -- CREATE TABLE IF NOT EXISTS `action_type` ( `action_type_id` int(11) NOT NULL AUTO_INCREMENT, `action_type_description` tinytext NOT NULL, PRIMARY KEY (`action_type_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ; -- -- Dumping data for table `action_type` -- INSERT INTO `action_type` (`action_type_id`, `action_type_description`) VALUES (1, 'INFORMATION'), (2, 'UNSCHEDULED OUTAGE'), (3, 'ACTION TYPE TEST'); -- -------------------------------------------------------- -- -- Table structure for table `assigned_group` -- CREATE TABLE IF NOT EXISTS `assigned_group` ( `assigned_group_id` int(11) NOT NULL AUTO_INCREMENT, `assigned_group_description` tinytext NOT NULL, PRIMARY KEY (`assigned_group_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ; -- -- Dumping data for table `assigned_group` -- INSERT INTO `assigned_group` (`assigned_group_id`, `assigned_group_description`) VALUES (1, 'MO-TMS OPS'), (2, 'TEST GROUP 2'), (3, 'TEST GROUP 3'); -- -------------------------------------------------------- -- -- Table structure for table `classification` -- CREATE TABLE IF NOT EXISTS `classification` ( `classification_id` int(11) NOT NULL AUTO_INCREMENT, `classification_description` tinytext NOT NULL, PRIMARY KEY (`classification_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; -- -- Dumping data for table `classification` -- INSERT INTO `classification` (`classification_id`, `classification_description`) VALUES (1, 'UNCLASSIFIED'), (2, 'CLASSIFIED'); -- -------------------------------------------------------- -- -- Table structure for table `community` -- CREATE TABLE IF NOT EXISTS `community` ( `community_id` int(11) NOT NULL AUTO_INCREMENT, `community_description` tinytext NOT NULL, PRIMARY KEY (`community_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; -- -- Dumping data for table `community` -- INSERT INTO `community` (`community_id`, `community_description`) VALUES (1, 'DISA'); -- -------------------------------------------------------- -- -- Table structure for table `domains` -- CREATE TABLE IF NOT EXISTS `domains` ( `domain_id` int(11) NOT NULL AUTO_INCREMENT, `domain_description` tinytext NOT NULL, PRIMARY KEY (`domain_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; -- -- Dumping data for table `domains` -- INSERT INTO `domains` (`domain_id`, `domain_description`) VALUES (1, 'Test Domain'); -- -------------------------------------------------------- -- -- Table structure for table `element_type` -- CREATE TABLE IF NOT EXISTS `element_type` ( `element_type_id` int(11) NOT NULL AUTO_INCREMENT, `element_type_description` tinytext NOT NULL, PRIMARY KEY (`element_type_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; -- -- Dumping data for table `element_type` -- INSERT INTO `element_type` (`element_type_id`, `element_type_description`) VALUES (1, 'Test element type'); -- -------------------------------------------------------- -- -- Table structure for table `fault_category` -- CREATE TABLE IF NOT EXISTS `fault_category` ( `fault_category_id` int(11) NOT NULL AUTO_INCREMENT, `fault_category_description` tinytext NOT NULL, PRIMARY KEY (`fault_category_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ; -- -- Dumping data for table `fault_category` -- INSERT INTO `fault_category` (`fault_category_id`, `fault_category_description`) VALUES (1, 'Category 1'), (2, 'Category 2'), (3, 'Category 3'); -- -------------------------------------------------------- -- -- Table structure for table `meta_action_info` -- CREATE TABLE IF NOT EXISTS `meta_action_info` ( `action_info_id` int(11) NOT NULL AUTO_INCREMENT, `ar_id` int(11) NOT NULL, `action_description_id` int(11) NOT NULL, `resolution_summary_id` int(11) NOT NULL, `community_id` int(11) NOT NULL, `op_impact_description` text NOT NULL, `zulu_date_time_out` datetime DEFAULT NULL, `zulu_date_time_in` datetime DEFAULT NULL, `outage_duration` float DEFAULT NULL, `request_source_id` int(11) DEFAULT NULL, `zulu_monitor_status_start` datetime DEFAULT NULL, `zulu_monitor_status_stop` datetime DEFAULT NULL, `zulu_date_time_etr` datetime DEFAULT NULL, `validation_source_id` int(11) DEFAULT NULL, `element_type_id` int(11) DEFAULT NULL, `element_id` tinytext, `validated` tinyint(1) DEFAULT NULL, `hit_si` varchar(255) DEFAULT NULL, `platform_domain_id` int(11) DEFAULT NULL, `action_type_id` int(11) NOT NULL, `priority_id` int(11) NOT NULL, `service1_id` int(11) NOT NULL, `service2_id` int(11) DEFAULT NULL, `service3_id` int(11) DEFAULT NULL, `submitter_site_id` int(11) NOT NULL, `supporting_site1_id` int(11) NOT NULL, `supporting_site2_id` int(11) NOT NULL, `assigned_group_id` int(11) NOT NULL, `assigned_technician_id` int(11) DEFAULT NULL, `on_call_pool` varchar(255) DEFAULT NULL, PRIMARY KEY (`action_info_id`), KEY `action_description_id` (`action_description_id`), KEY `impacted_community_id` (`community_id`), KEY `request_source_id` (`request_source_id`), KEY `validation_source_id` (`validation_source_id`), KEY `platform_domain_id` (`platform_domain_id`), KEY `priority_id` (`priority_id`), KEY `service1_id` (`service1_id`), KEY `service2_id` (`service2_id`), KEY `service3_id` (`service3_id`), KEY `submitter_site_id` (`submitter_site_id`), KEY `supporting_site1_id` (`supporting_site1_id`), KEY `supporting_site2_id` (`supporting_site2_id`), KEY `assigned_group_id` (`assigned_group_id`), KEY `assigned_technician_id` (`assigned_technician_id`), KEY `action_type_id` (`action_type_id`), KEY `ar_id` (`ar_id`), KEY `resolution_summary_id` (`resolution_summary_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ; -- -- Dumping data for table `meta_action_info` -- INSERT INTO `meta_action_info` (`action_info_id`, `ar_id`, `action_description_id`, `resolution_summary_id`, `community_id`, `op_impact_description`, `zulu_date_time_out`, `zulu_date_time_in`, `outage_duration`, `request_source_id`, `zulu_monitor_status_start`, `zulu_monitor_status_stop`, `zulu_date_time_etr`, `validation_source_id`, `element_type_id`, `element_id`, `validated`, `hit_si`, `platform_domain_id`, `action_type_id`, `priority_id`, `service1_id`, `service2_id`, `service3_id`, `submitter_site_id`, `supporting_site1_id`, `supporting_site2_id`, `assigned_group_id`, `assigned_technician_id`, `on_call_pool`) VALUES (2, 1, 1, 1, 1, 'TEST TICKET IMPACT DESCRIPTION', '2014-08-19 00:00:00', NULL, 2.31, 1, NULL, NULL, NULL, 1, 1, NULL, NULL, NULL, 1, 1, 1, 1, 2, NULL, 2, 5, 2, 1, 1, NULL), (3, 2, 2, 2, 1, 'TEST 2', '2014-08-19 00:00:00', NULL, 2.31, 1, NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, 1, 2, 2, 3, 5, 1, 5, 4, 5, 2, 2, NULL), (4, 3, 3, 1, 1, 'TEST 3', '2014-08-19 00:00:00', NULL, 2.31, 1, NULL, NULL, NULL, 2, 1, NULL, NULL, NULL, 1, 3, 3, 1, 1, 1, 4, 1, 1, 3, 1, NULL), (5, 4, 1, 1, 1, 'TEST 4', '2014-08-19 00:00:00', NULL, 2.31, 1, NULL, NULL, NULL, 2, 1, NULL, NULL, NULL, 1, 1, 4, 1, 1, 1, 1, 1, 1, 2, 2, NULL), (6, 5, 1, 1, 1, 'TEST 5', '2014-08-19 00:00:00', NULL, 2.31, 1, NULL, NULL, NULL, 2, 1, NULL, NULL, NULL, 1, 2, 5, 1, 1, 1, 1, 1, 1, 1, 1, NULL); -- -------------------------------------------------------- -- -- Table structure for table `meta_action_requests` -- CREATE TABLE IF NOT EXISTS `meta_action_requests` ( `ar_id` int(11) NOT NULL AUTO_INCREMENT, `ar_number` varchar(25) NOT NULL, `action_type_id` int(11) NOT NULL, `assigned_group_id` int(11) DEFAULT NULL, `status_id` int(11) NOT NULL, `high_level_outage` varchar(255) DEFAULT NULL, `low_level_outage` varchar(255) DEFAULT NULL, `submitter_id` int(11) NOT NULL, `quicket_id` int(11) DEFAULT NULL, `classification_id` int(11) NOT NULL, `ar_delete` tinyint(1) NOT NULL DEFAULT '0', `description` text NOT NULL, PRIMARY KEY (`ar_id`), KEY `ar_group` (`assigned_group_id`), KEY `status` (`status_id`), KEY `submiter` (`submitter_id`), KEY `quicket_type` (`quicket_id`), KEY `classification` (`classification_id`), KEY `action_type_id` (`action_type_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ; -- -- Dumping data for table `meta_action_requests` -- INSERT INTO `meta_action_requests` (`ar_id`, `ar_number`, `action_type_id`, `assigned_group_id`, `status_id`, `high_level_outage`, `low_level_outage`, `submitter_id`, `quicket_id`, `classification_id`, `ar_delete`, `description`) VALUES (1, 'WE K-00000001', 1, 1, 1, 'High Level Outage', 'Low Level Outage', 1, NULL, 1, 0, 'TEST TICKET 1'), (2, 'WE K-00000002', 1, 2, 2, 'High Level Outage', 'Low Level Outage', 2, 2, 2, 0, 'TEST TICKET 2'), (3, 'WE K-00000003', 1, 3, 2, 'High Level Outage', 'Low Level Outage', 1, 3, 1, 1, 'TEST TICKET 3'), (4, 'WE K-00000004', 1, 1, 1, 'High Level Outage', 'Low Level Outage', 2, 4, 2, 0, 'TEST TICKET 4'), (5, 'WE K-00000005', 1, 1, 1, 'High Level Outage', 'Low Level Outage', 1, 5, 1, 0, 'TEST TICKET 5'); -- -------------------------------------------------------- -- -- Table structure for table `meta_fault_summary` -- CREATE TABLE IF NOT EXISTS `meta_fault_summary` ( `fault_id` int(11) NOT NULL AUTO_INCREMENT, `ar_id` int(11) NOT NULL, `fault_date_time_out` datetime NOT NULL, `fault_date_time_in` datetime DEFAULT NULL, `service4_id` int(11) DEFAULT NULL, `fault_duration` decimal(10,0) DEFAULT NULL, `fault_location_id` int(11) DEFAULT NULL, `fault_category_id` int(11) DEFAULT NULL, `rfo1_id` int(11) DEFAULT NULL, `rfo2_id` int(11) DEFAULT NULL, `vendor_id` int(11) DEFAULT NULL, `vendor_ticket_number` tinytext, `rfo_remarks` text, PRIMARY KEY (`fault_id`), KEY `ar_id` (`ar_id`), KEY `service4_id` (`service4_id`), KEY `fault_location_id` (`fault_location_id`), KEY `fault_category_id` (`fault_category_id`), KEY `rfo1_id` (`rfo1_id`), KEY `rfo2_id` (`rfo2_id`), KEY `vendor_id` (`vendor_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ; -- -- Dumping data for table `meta_fault_summary` -- INSERT INTO `meta_fault_summary` (`fault_id`, `ar_id`, `fault_date_time_out`, `fault_date_time_in`, `service4_id`, `fault_duration`, `fault_location_id`, `fault_category_id`, `rfo1_id`, `rfo2_id`, `vendor_id`, `vendor_ticket_number`, `rfo_remarks`) VALUES (1, 1, '2014-08-20 00:00:00', NULL, 3, '3', 1, 1, 1, 2, 4, NULL, 'Reason for outage was due to failing PSU in DC.'), (2, 2, '2014-08-20 00:00:00', '2014-09-01 00:00:00', 1, NULL, 2, 2, 2, 3, 3, '12345', 'Outage caused due to cut in cable.'), (3, 3, '2014-08-20 00:00:00', NULL, 2, '2', 3, 3, 3, 4, 2, NULL, 'The cause of this outage is unknown.'), (4, 4, '2014-08-20 00:00:00', NULL, 5, NULL, 4, 2, 4, 3, 1, NULL, 'Outage caused due to generator failure.'), (5, 5, '2014-08-20 00:00:00', NULL, 4, '25', 5, 1, 2, 1, 2, '54321', 'Outage caused due to hurricane.'); -- -------------------------------------------------------- -- -- Table structure for table `platform` -- CREATE TABLE IF NOT EXISTS `platform` ( `platform_id` int(11) NOT NULL AUTO_INCREMENT, `platform_description` tinytext NOT NULL, PRIMARY KEY (`platform_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; -- -- Dumping data for table `platform` -- INSERT INTO `platform` (`platform_id`, `platform_description`) VALUES (1, 'Test Platform'); -- -------------------------------------------------------- -- -- Table structure for table `priority` -- CREATE TABLE IF NOT EXISTS `priority` ( `priority_id` int(11) NOT NULL AUTO_INCREMENT, `priority_description` tinytext NOT NULL, PRIMARY KEY (`priority_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ; -- -- Dumping data for table `priority` -- INSERT INTO `priority` (`priority_id`, `priority_description`) VALUES (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'); -- -------------------------------------------------------- -- -- Table structure for table `quicket` -- CREATE TABLE IF NOT EXISTS `quicket` ( `quicket_id` int(11) NOT NULL AUTO_INCREMENT, `quicket_description` tinytext NOT NULL, PRIMARY KEY (`quicket_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ; -- -- Dumping data for table `quicket` -- INSERT INTO `quicket` (`quicket_id`, `quicket_description`) VALUES (1, 'Test Quicket'), (2, 'QUICKET 1'), (3, 'QUICKET 2'), (4, 'QUICKET 3'), (5, 'QUICKET 4'); -- -------------------------------------------------------- -- -- Table structure for table `rfo` -- CREATE TABLE IF NOT EXISTS `rfo` ( `rfo_id` int(11) NOT NULL AUTO_INCREMENT, `rfo_description` tinytext NOT NULL, PRIMARY KEY (`rfo_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ; -- -- Dumping data for table `rfo` -- INSERT INTO `rfo` (`rfo_id`, `rfo_description`) VALUES (1, 'RFO 1'), (2, 'RFO 2'), (3, 'RFO 3'), (4, 'RFO 4'); -- -------------------------------------------------------- -- -- Table structure for table `service` -- CREATE TABLE IF NOT EXISTS `service` ( `service_id` int(11) NOT NULL AUTO_INCREMENT, `service_description` tinytext NOT NULL, PRIMARY KEY (`service_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ; -- -- Dumping data for table `service` -- INSERT INTO `service` (`service_id`, `service_description`) VALUES (1, 'COMPUTING'), (2, 'OTHER CUSTOMER SUPPORT'), (3, 'MISCELLANEOUS'), (4, 'APPLICATIONS'), (5, 'DMS-BLACK'); -- -------------------------------------------------------- -- -- Table structure for table `site` -- CREATE TABLE IF NOT EXISTS `site` ( `site_id` int(11) NOT NULL AUTO_INCREMENT, `site_description` tinytext NOT NULL, PRIMARY KEY (`site_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ; -- -- Dumping data for table `site` -- INSERT INTO `site` (`site_id`, `site_description`) VALUES (1, 'DISA CS MO TECH SUPPORT'), (2, 'SMC-TECH SPT'), (3, 'MONTGOMERY'), (4, 'GNC DCTS NOC'), (5, 'TNC'), (6, 'PAC'); -- -------------------------------------------------------- -- -- Table structure for table `source` -- CREATE TABLE IF NOT EXISTS `source` ( `source_id` int(11) NOT NULL AUTO_INCREMENT, `source_description` tinytext NOT NULL, PRIMARY KEY (`source_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; -- -- Dumping data for table `source` -- INSERT INTO `source` (`source_id`, `source_description`) VALUES (1, 'Test Source 1'), (2, 'Test Source 2'); -- -------------------------------------------------------- -- -- Table structure for table `status` -- CREATE TABLE IF NOT EXISTS `status` ( `status_id` int(11) NOT NULL AUTO_INCREMENT, `status_description` tinytext NOT NULL, PRIMARY KEY (`status_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; -- -- Dumping data for table `status` -- INSERT INTO `status` (`status_id`, `status_description`) VALUES (1, 'IN PROGRESS'), (2, 'CLOSED'); -- -------------------------------------------------------- -- -- Table structure for table `summary` -- CREATE TABLE IF NOT EXISTS `summary` ( `summary_id` int(11) NOT NULL AUTO_INCREMENT, `summary_description` text NOT NULL, PRIMARY KEY (`summary_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; -- -- Dumping data for table `summary` -- INSERT INTO `summary` (`summary_id`, `summary_description`) VALUES (1, 'This is a test of the summary field.'), (2, 'This is another test of the summary field.'); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE IF NOT EXISTS `users` ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `username` tinytext NOT NULL, `password` tinytext NOT NULL, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; -- -- Dumping data for table `users` -- INSERT INTO `users` (`user_id`, `username`, `password`) VALUES (1, 'REMEDY', '<PASSWORD>'), (2, 'user1', '<PASSWORD>'); -- -------------------------------------------------------- -- -- Table structure for table `vendor` -- CREATE TABLE IF NOT EXISTS `vendor` ( `vendor_id` int(11) NOT NULL AUTO_INCREMENT, `vendor_description` tinytext NOT NULL, PRIMARY KEY (`vendor_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ; -- -- Dumping data for table `vendor` -- INSERT INTO `vendor` (`vendor_id`, `vendor_description`) VALUES (1, 'Vendor 1'), (2, 'Vendor 2'), (3, 'Vendor 3'), (4, 'Vendor 4'); -- -- Constraints for dumped tables -- -- -- Constraints for table `meta_action_info` -- ALTER TABLE `meta_action_info` ADD CONSTRAINT `meta_action_info_ibfk_1` FOREIGN KEY (`community_id`) REFERENCES `community` (`community_id`), ADD CONSTRAINT `meta_action_info_ibfk_10` FOREIGN KEY (`service2_id`) REFERENCES `service` (`service_id`), ADD CONSTRAINT `meta_action_info_ibfk_11` FOREIGN KEY (`service3_id`) REFERENCES `service` (`service_id`), ADD CONSTRAINT `meta_action_info_ibfk_12` FOREIGN KEY (`supporting_site1_id`) REFERENCES `site` (`site_id`), ADD CONSTRAINT `meta_action_info_ibfk_13` FOREIGN KEY (`supporting_site2_id`) REFERENCES `site` (`site_id`), ADD CONSTRAINT `meta_action_info_ibfk_14` FOREIGN KEY (`assigned_group_id`) REFERENCES `assigned_group` (`assigned_group_id`), ADD CONSTRAINT `meta_action_info_ibfk_15` FOREIGN KEY (`ar_id`) REFERENCES `meta_action_requests` (`ar_id`), ADD CONSTRAINT `meta_action_info_ibfk_16` FOREIGN KEY (`action_description_id`) REFERENCES `action_descriptions` (`action_description_id`), ADD CONSTRAINT `meta_action_info_ibfk_2` FOREIGN KEY (`request_source_id`) REFERENCES `source` (`source_id`), ADD CONSTRAINT `meta_action_info_ibfk_3` FOREIGN KEY (`platform_domain_id`) REFERENCES `platform` (`platform_id`), ADD CONSTRAINT `meta_action_info_ibfk_4` FOREIGN KEY (`action_type_id`) REFERENCES `action_type` (`action_type_id`), ADD CONSTRAINT `meta_action_info_ibfk_5` FOREIGN KEY (`priority_id`) REFERENCES `priority` (`priority_id`), ADD CONSTRAINT `meta_action_info_ibfk_6` FOREIGN KEY (`service1_id`) REFERENCES `service` (`service_id`), ADD CONSTRAINT `meta_action_info_ibfk_7` FOREIGN KEY (`submitter_site_id`) REFERENCES `site` (`site_id`), ADD CONSTRAINT `meta_action_info_ibfk_8` FOREIGN KEY (`assigned_technician_id`) REFERENCES `users` (`user_id`), ADD CONSTRAINT `meta_action_info_ibfk_9` FOREIGN KEY (`validation_source_id`) REFERENCES `source` (`source_id`); -- -- Constraints for table `meta_action_requests` -- ALTER TABLE `meta_action_requests` ADD CONSTRAINT `classification_description` FOREIGN KEY (`classification_id`) REFERENCES `classification` (`classification_id`), ADD CONSTRAINT `group_description` FOREIGN KEY (`assigned_group_id`) REFERENCES `assigned_group` (`assigned_group_id`), ADD CONSTRAINT `meta_action_requests_ibfk_2` FOREIGN KEY (`submitter_id`) REFERENCES `users` (`user_id`), ADD CONSTRAINT `meta_action_requests_ibfk_3` FOREIGN KEY (`action_type_id`) REFERENCES `action_type` (`action_type_id`), ADD CONSTRAINT `quicket_description` FOREIGN KEY (`quicket_id`) REFERENCES `quicket` (`quicket_id`), ADD CONSTRAINT `status_description` FOREIGN KEY (`status_id`) REFERENCES `status` (`status_id`); -- -- Constraints for table `meta_fault_summary` -- ALTER TABLE `meta_fault_summary` ADD CONSTRAINT `meta_fault_summary_ibfk_1` FOREIGN KEY (`ar_id`) REFERENCES `meta_action_requests` (`ar_id`), ADD CONSTRAINT `meta_fault_summary_ibfk_2` FOREIGN KEY (`service4_id`) REFERENCES `service` (`service_id`), ADD CONSTRAINT `meta_fault_summary_ibfk_3` FOREIGN KEY (`fault_location_id`) REFERENCES `site` (`site_id`), ADD CONSTRAINT `meta_fault_summary_ibfk_4` FOREIGN KEY (`fault_category_id`) REFERENCES `fault_category` (`fault_category_id`), ADD CONSTRAINT `meta_fault_summary_ibfk_5` FOREIGN KEY (`rfo1_id`) REFERENCES `rfo` (`rfo_id`), ADD CONSTRAINT `meta_fault_summary_ibfk_6` FOREIGN KEY (`rfo2_id`) REFERENCES `rfo` (`rfo_id`), ADD CONSTRAINT `meta_fault_summary_ibfk_7` FOREIGN KEY (`vendor_id`) REFERENCES `vendor` (`vendor_id`); /*!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 */; <file_sep>/classes/class.database.php <?php require_once("config.database.php"); class Database { private $host = DB_HOST; private $user = DB_USER; private $pass = <PASSWORD>; private $database = DB_NAME; private $db_handle; private $db_error; private $statement; public function __construct() { // Create the DSN connection string $dsn = "mysql:dbname=" . $this->database . ";host=" . $this->host; // Define options for the PDO connection $pdo_options = array( PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ); try { $this->db_handle = new PDO($dsn, $this->user, $this->pass, $pdo_options); } catch(PDOExcetion $e) { $this->db_error = $e->getMessage(); } } public function query($query) { $this->statement = $this->db_handle->prepare($query); } public function bind($param, $value, $type = null) { if(is_null($type)) { switch(true) { case is_int($value): $type = PDO::PARAM_INT; break; case is_bool($value): $type = PDO::PARAM_BOOL; break; case is_null($value): $type = PDO::PARAM_NULL; break; default: $type = PDO::PARAM_STR; } } $this->statement->bindValue($param, $value, $type); } public function execute() { return $this->statement->execute(); } public function resultSet() { $this->execute(); return $this->statement->fetchAll(PDO::FETCH_ASSOC); } public function single() { $this->execute(); return $this->statement->fetch(PDO::FETCH_ASSOC); } public function update() { $this->execute(); } public function insert() { $this->execute(); return $this->db_handle->lastInsertId(); } } ?><file_sep>/index.php <!doctype html> <?php require_once("template_engine.php"); ?> <html lang="en"> <head> <meta charset="utf-8"> <title>Global Trouble Management System</title> <script src="js/external/jquery/jquery.js"></script> <script src="js/jquery-ui.js"></script> <script src="js/flexgrid/js/flexigrid.js"></script> <!--<script src="js/flexgrid/js/flexigrid.pack.js"></script>--> <script src="js/gtms.js"></script> <link rel="stylesheet" href="js/jquery-ui.css"> <link rel="stylesheet" href="js/flexgrid/css/flexigrid.css"> <link rel="stylesheet" href="css/styles.css"> </head> <body> <div id="main_container"> <div id="tickets_container" class="ui-widget-content"> <div id="tickets_header"> Matching Tm Action Request </div> <div id="tickets_grid_container"> <table class="flex1" style="display: none"></table> </div> </div> <div id="details_container" class="ui-widget-content"> <div id="details_header"> Modify Tm Action Request <form action="new_ticket.php" style="display:inline"> <input type="submit" id="new_ticket" value="New AR" /> </form> <input type="button" id="update_ticket" value="Save Changes" /> </div> <div id="status_container"> <div class="box1"> <i>AR Number</i><br /> <input id="ar_number" type="text" value="" disabled=true /> </div> <div id="status" class="box1"> Status<br /> <?php echo getDropDown("status"); ?> </div> <div id="higher_level_outage" class="box1"> Higher Level Outage<br /> <input id="high_level_outage" type="text" value="" /> </div> <div class="box1"> Lower Level Outage<br /> <input id="low_level_outage" type="text" value="" disabled=true size="1" /> </div> <div class="box1"> <strong>Submitter</strong><br /> <input id="submitter" type="text" value="" disabled=true /> </div> <div class="box1"> Record Classification<br /> <?php echo getDropDown("classification"); ?> </div> <!-- commenting this out since deleting will not be necessary for this training exercise --> <!-- <div class="box1"> Delete<br /> <select id="delete"> <option value="" selected>&nbsp;</option> <option value="no">No</option> <option value="yes">Yes</option> </select> </div> --> </div> <!-- <div id="button_container"> <input type="button" value="View AR Report" class="button" /> <input type="button" value="Spell Check" class="button" /> <input type="button" value="Find Higher Level Outage" class="button" /> <input type="button" value="View Relationship" class="button" /> <input type="button" value="Copy to New" class="button" /> <input type="button" value="View Priority Instructions" class="button" /> <input type="button" value="Open Action Req Guide" class="button" /> </div> --> <div id="action_tab_container" class="tab_container"> <ul> <li><a href="#contact_info">Contact Info</a></li> <li><a href="#action_info">Action Info</a></li> </ul> <div id="contact_info">Contact Information</div> <div id="action_info"> <div id="action_description_container"> <span class="required_input">Action Description</span><br /> <textarea id="action_description_text"></textarea> <br /> <span class="not_required_input">Status or Resolution Summary</span><br /> <textarea id="resolution_text"></textarea> </div> <div id="impacted_container"> <div class="required_input inline_block"> Impact Communities<br /> <?php echo getDropDown("community"); ?> </div> <br /> <div class="inline_block"> Zulu Date Time Out<br /> <input id="zulu_date_time_out" type="text" value="" disabled="true" /> </div> <div class="inline_block"> Zulu Date Time In<br /> <input id="zulu_date_time_in" type="text" value="" disabled="true" /> </div> <div class="inline_block"> Outage Duration Hours<br /> <input id="outage_duration" type="text" value="" disabled="true" /> </div> <div class="inline_block"> Request Source<br /> <?php echo getDropDown("source", "request"); ?> </div> <br /> <div class="inline_block"> Zulu Monitor Status Start +<br /> <input id="zulu_monitor_status_start" type="text" value="" /> </div> <div class="inline_block"> Zulu Monitor Status Stop +<br /> <input id="zulu_monitor_status_stop" type="text" value="" /> </div> <div class="inline_block"> Zulu Date Time ETR +<br /> <input id="zulu_date_time_etr" type="text" value="" /> </div> </div> <div id="validation_container"> <div class="inline_block"> Validation Source<br /> <?php echo getDropDown("source", "validation"); ?> </div> <div class="inline_block"> Element ID Type<br /> <?php echo getDropDown("element_type"); ?> </div> <div class="inline_block"> Element ID +<br /> <input id="element_id" type="text" value="" /> </div> <div class="inline_block"> Replace Subform<br /> <select id="replace_subform"> <option value="" selected>&nbsp;</option> <option value="no">No</option> <option value="yes">Yes</option> </select> </div> <div class="inline_block"> Platform or Domain<br /> <?php echo getDropDown("platform", "domain"); ?> </div> <br /> <div class="required_input inline_block"> Action Type<br /> <?php echo getDropDown("action_type"); ?> </div> <div class="required_input inline_block"> Assigned Priority<br /> <?php echo getDropDown("priority"); ?> </div> <div class="required_input inline_block"> Service 1<br /> <?php echo getDropDown("service", "", "service1"); ?> </div> <div class="required_input inline_block"> Service 2<br /> <?php echo getDropDown("service", "", "service2"); ?> </div> <div class="required_input inline_block"> Service 3<br /> <?php echo getDropDown("service", "", "service3"); ?> </div> <br /> <div class="required_input inline_block"> Submitter Site<br /> <?php echo getDropDown("site", "submitter", "submitter_site"); ?> </div> <div class="required_input inline_block"> Supporting Site 1<br /> <?php echo getDropDown("site", "", "supporting_site1"); ?> </div> <div class="required_input inline_block"> Supporting Site 2<br /> <?php echo getDropDown("site", "", "supporting_site2"); ?> </div> <div class="required_input inline_block"> Assigned Group<br /> <?php echo getDropDown("assigned_group"); ?> </div> <div class="required_input inline_block"> On Call Pool<br /> <input type="text" value="" disabled="true" /> </div> </div> </div> </div> </div> <div id="details_tab_container" class="tab_container"> <ul> <li><a href="#fault_summary">Fault Summary</a></li> <li><a href="#reporting">Reporting</a></li> <li><a href="#comm">COMM</a></li> <li><a href="#dms">DMS</a></li> <li><a href="#hardware">Hardware</a></li> <li><a href="#software">Software</a></li> <li><a href="#work_order">Work Order</a></li> <li><a href="#subform">Subform</a></li> <li><a href="#history">History</a></li> </ul> <div id="fault_summary"> <div id="fault_container"> <div class="required_input inline_block"> Zulu Fault Date Time Out +<br /> <input id="zulu_fault_date_time_out" type="text" width="130px" /> </div> <div class="inline_block"> Zulu Fault Date Time In +<br /> <input id="zulu_fault_date_time_in" type="text" width="130px" /> </div> <div class="inline_block"> Service 4<br /> <?php echo getDropDown("service", "", "service4"); ?> </div> <div class="inline_block"> Fault Duration Hours<br /> <input id="fault_duration" type="text" disabled="true" /> </div> <div class="inline_block"> Location of Problem +<br /> <?php echo getDropDown("site", "", "fault_location_id"); ?> </div> <br /> <div class="inline_block"> Fault Category<br /> <?php echo getDropDown("fault_category"); ?> </div> <div class="inline_block"> RFO 1<br /> <?php echo getDropDown("rfo", "", "rfo1"); ?> </div> <div class="inline_block"> RFO 2<br /> <?php echo getDropDown("rfo", "", "rfo2"); ?> </div> <div class="inline_block"> Vendor<br /> <?php echo getDropDown("vendor"); ?> </div> <div class="inline_block"> Vendor Ticket Number<br /> <input id="vendor_ticket_number" type="text" value="" disabled="true" /> </div> <br /> <div class="inline_block"> RFO Remarks<br /> <input id="rfo_remarks" type="text" value="" style="width:600px" /> </div> <br /><br /> <table class="flex2" style="display: none"></table> </div> </div> <div id="reporting">Reporting</div> <div id="comm">COMM</div> <div id="dms">DMS</div> <div id="hardware">Hardware</div> <div id="software">Software</div> <div id="work_order">Work Order</div> <div id="subform">Subform</div> <div id="history">History</div> </div> </div> </body> </html> <file_sep>/api/create_action_request.php <?php if(isset($_POST['meta_action_requests'])) { require_once("../classes/class.database.php"); $db = new Database(); // Array for each query to be performed. $query = Array(); // ar_id for meta tables $ar_id; // have to pull this out special because the group_id occurs in both the action_request table and the action_info table. // not a good way to do it, but too far down the rabbit hole to change. $group_id = $_POST['meta_action_info']['assigned_group_id']; $action_type = $_POST['meta_action_info']['action_type_id']; $description = $_POST['meta_action_info']['action_description']; // We need to get the last inserted AR Nmuber and increment it by one. Since this is a alpha-numeric value // auto-increment won't work in this circumstance. We are making the assumption the tickets will be limited to // 8 place holders or less, meaning we are limited to 99,999,999 unique tickets. If this isn't enough, we should // probably consider refactoring this application. $ar_query = "SELECT ar_number FROM meta_action_requests ORDER BY ar_id DESC LIMIT 1"; $db->query($ar_query); $old_ar_num = $db->single(); $new_ar_num = substr($old_ar_num['ar_number'], 0, -8) . substr($old_ar_num['ar_number'], -8, -1) . (1+substr($old_ar_num['ar_number'], -1)); // Iterate through the posted variables and build query strings foreach($_POST as $table=>$params) { while('NULL' === end($params)) array_pop($params); $last_key = end(array_keys($params)); $columns = "("; $values = "("; if($table == "meta_action_requests") { $columns .= "ar_number, "; $values .= "'$new_ar_num', "; } else { $columns .= "ar_id, "; $values .= "':ar_id', "; } if($group_id !== null && $table == "meta_action_requests") { $columns .= "assigned_group_id, "; $values .= "'$group_id', "; } // if($action_type !== null && $table == "meta_action_requests") { // $columns .= "action_type_id, "; // $values .= "'$action_type', "; // } if($description !== null && $table == "meta_action_requests") { $columns .= "description, "; $values .= "'$description', "; } // echo "Last Key: $last_key\n"; // print_r($params); foreach($params as $field=>$value) { if($value !== 'NULL') { $columns .= $field; $columns .= ($field !== $last_key) ? ", " : ")"; $values .= "'$value'"; $values .= ($field !== $last_key) ? ", " : ")"; } } $query[$table] = "INSERT INTO $table $columns VALUES $values;"; } echo "<pre>\n"; print_r($query); echo "</pre>\n"; foreach($query as $key => $q_string) { if($key == "meta_action_requests") { $db->query($q_string); $ar_id = $db->insert(); } else { $q_string = str_replace(":ar_id", $ar_id, $q_string); $db->query($q_string); $db->insert(); } } } ?><file_sep>/api/ar_grid.php <?php require_once("../classes/class.database.php"); $db = new Database(); $page = isset($_POST['page']) ? $_POST['page'] : 1; $rp = isset($_POST['rp']) ? $_POST['rp'] : 10; $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'name'; $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc'; $query = isset($_POST['query']) ? $_POST['query'] : false; $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : false; $db->query(" SELECT ar.ar_id, ar_number, status.status_description, assigned_group.assigned_group_description, meta_action_info.zulu_date_time_out, ar.action_type_id, action_type_description, description FROM meta_action_requests AS ar LEFT JOIN status ON ar.status_id = status.status_id LEFT JOIN assigned_group ON ar.assigned_group_id = assigned_group.assigned_group_id LEFT JOIN meta_action_info ON ar.ar_id = meta_action_info.ar_id LEFT JOIN action_type ON ar.action_type_id = action_type.action_type_id; "); $rows = $db->resultSet(); if($qtype && $query){ $query = strtolower(trim($query)); foreach($rows AS $key => $row){ if(strpos(strtolower($row[$qtype]),$query) === false){ unset($rows[$key]); } } } $sortArray = array(); foreach($rows AS $key => $row){ $sortArray[$key] = $row[$sortname]; } $sortMethod = SORT_ASC; if($sortorder == 'desc'){ $sortMethod = SORT_DESC; } array_multisort($sortArray, $sortMethod, $rows); $total = count($rows); $rows = array_slice($rows,($page-1)*$rp,$rp); $jsonData = array('page'=>1,'total'=>0,'rows'=>array()); foreach($rows AS $rowNum => $row){ //If cell's elements have named keys, they must match column names //Only cell's with named keys and matching columns are order independent. $entry = array('id' => ($rowNum+1), 'cell'=>array( 'ar_id' => $row['ar_id'], // This is temporary to allow for dummy data 'ar_number' => $row['ar_number'], 'status_description' => $row['status_description'], 'assigned_group_description' => $row['assigned_group_description'], 'zulu_date_time_out' => $row['zulu_date_time_out'], 'action_type_description' => $row['action_type_description'], 'description' => $row['description'] ) ); $jsonData['rows'][] = $entry; } $jsonData['total'] = count($rows); echo json_encode($jsonData); ?><file_sep>/api/action_requests.php <?php require_once("../classes/class.database.php"); if(isset($_GET['ar_id'])) { $db = new Database(); $db->query(" SELECT ar_id, ar_number, action_type_description, assigned_group.assigned_group_description, status_id, high_level_outage, low_level_outage, users.username, quicket_id, classification_id, ar_delete, description FROM meta_action_requests AS ar LEFT JOIN action_type ON ar.action_type_id = action_type.action_type_id LEFT JOIN assigned_group ON ar.assigned_group_id = assigned_group.assigned_group_id LEFT JOIN users ON ar.submitter_id = users.user_id WHERE ar_id = :ar_id; "); $db->bind(":ar_id", $_GET['ar_id'], 3); $action_requests = $db->resultSet(); echo json_encode($action_requests); } else { $db = new Database(); $db->query(" SELECT ar_id, ar_number, action_type_description, assigned_group.assigned_group_description, status.status_description, high_level_outage, low_level_outage, users.username, quicket.quicket_description, classification.classification_description, ar_delete, description FROM meta_action_requests AS ar LEFT JOIN action_type ON ar.action_type_id = action_type.action_type_id LEFT JOIN assigned_group ON ar.assigned_group_id = assigned_group.assigned_group_id LEFT JOIN status ON ar.status_id = status.status_id LEFT JOIN users ON ar.submitter_id = users.user_id LEFT JOIN quicket ON ar.quicket_id = quicket.quicket_id LEFT JOIN classification ON ar.classification_id = classification.classification_id; "); $action_requests = $db->resultSet(); print_r(json_encode($action_requests)); } ?><file_sep>/api/fault_summary.php <?php require_once("../classes/class.database.php"); if(isset($_GET['ar_id'])) { $db = new Database(); $db->query(" SELECT fault_id, ar_id, fault_date_time_out, fault_date_time_in, service4_id, fault_duration, fault_location_id, fault_category_id, rfo1_id, rfo2_id, vendor_id, vendor_ticket_number, rfo_remarks FROM meta_fault_summary AS fs WHERE ar_id = :ar_id "); $db->bind(":ar_id", $_GET['ar_id'], 3); $action_requests = $db->resultSet(); print_r(json_encode($action_requests)); } else { echo "Restricted"; } ?><file_sep>/database_exports/20141030.sql -- phpMyAdmin SQL Dump -- version 4.0.10deb1 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Oct 30, 2014 at 10:04 AM -- Server version: 5.5.38-0ubuntu0.14.04.1 -- PHP Version: 5.5.9-1ubuntu4.3 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!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 */; /*!40101 SET NAMES utf8 */; -- -- Database: `gtms` -- -- -------------------------------------------------------- -- -- Table structure for table `action_type` -- CREATE TABLE IF NOT EXISTS `action_type` ( `action_type_id` int(11) NOT NULL AUTO_INCREMENT, `action_type_description` tinytext NOT NULL, PRIMARY KEY (`action_type_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ; -- -- Dumping data for table `action_type` -- INSERT INTO `action_type` (`action_type_id`, `action_type_description`) VALUES (1, 'INFORMATION'), (2, 'UNSCHEDULED OUTAGE'), (3, 'ACTION TYPE TEST'), (4, 'ASI'); -- -------------------------------------------------------- -- -- Table structure for table `assigned_group` -- CREATE TABLE IF NOT EXISTS `assigned_group` ( `assigned_group_id` int(11) NOT NULL AUTO_INCREMENT, `assigned_group_description` tinytext NOT NULL, PRIMARY KEY (`assigned_group_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=21 ; -- -- Dumping data for table `assigned_group` -- INSERT INTO `assigned_group` (`assigned_group_id`, `assigned_group_description`) VALUES (1, 'MO-TMS OPS'), (2, 'TEST GROUP 2'), (3, 'TEST GROUP 3'), (4, 'Net Assurance'), (5, 'DCCC'), (6, 'OTN'), (7, 'MTT'), (8, 'CNDSP'), (9, 'ASI'), (10, 'TMD'), (11, 'NIC'), (12, 'GSM-0 II'), (13, 'Promina NOC'), (14, 'GCN OSC'), (15, 'Commercial'), (16, 'DSN/DRSN NOC'), (17, 'IP/ATM'), (18, 'DMS NOC'), (19, 'Tier II Trans'), (20, 'DVS'); -- -------------------------------------------------------- -- -- Table structure for table `classification` -- CREATE TABLE IF NOT EXISTS `classification` ( `classification_id` int(11) NOT NULL AUTO_INCREMENT, `classification_description` tinytext NOT NULL, PRIMARY KEY (`classification_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; -- -- Dumping data for table `classification` -- INSERT INTO `classification` (`classification_id`, `classification_description`) VALUES (1, 'UNCLASSIFIED'), (2, 'CLASSIFIED'); -- -------------------------------------------------------- -- -- Table structure for table `community` -- CREATE TABLE IF NOT EXISTS `community` ( `community_id` int(11) NOT NULL AUTO_INCREMENT, `community_description` tinytext NOT NULL, PRIMARY KEY (`community_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; -- -- Dumping data for table `community` -- INSERT INTO `community` (`community_id`, `community_description`) VALUES (1, 'DISA'); -- -------------------------------------------------------- -- -- Table structure for table `domains` -- CREATE TABLE IF NOT EXISTS `domains` ( `domain_id` int(11) NOT NULL AUTO_INCREMENT, `domain_description` tinytext NOT NULL, PRIMARY KEY (`domain_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; -- -- Dumping data for table `domains` -- INSERT INTO `domains` (`domain_id`, `domain_description`) VALUES (1, 'Test Domain'); -- -------------------------------------------------------- -- -- Table structure for table `element_type` -- CREATE TABLE IF NOT EXISTS `element_type` ( `element_type_id` int(11) NOT NULL AUTO_INCREMENT, `element_type_description` tinytext NOT NULL, PRIMARY KEY (`element_type_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; -- -- Dumping data for table `element_type` -- INSERT INTO `element_type` (`element_type_id`, `element_type_description`) VALUES (1, 'Test element type'); -- -------------------------------------------------------- -- -- Table structure for table `fault_category` -- CREATE TABLE IF NOT EXISTS `fault_category` ( `fault_category_id` int(11) NOT NULL AUTO_INCREMENT, `fault_category_description` tinytext NOT NULL, PRIMARY KEY (`fault_category_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ; -- -- Dumping data for table `fault_category` -- INSERT INTO `fault_category` (`fault_category_id`, `fault_category_description`) VALUES (1, 'Category 1'), (2, 'Category 2'), (3, 'Category 3'); -- -------------------------------------------------------- -- -- Table structure for table `meta_action_info` -- CREATE TABLE IF NOT EXISTS `meta_action_info` ( `action_info_id` int(11) NOT NULL AUTO_INCREMENT, `ar_id` int(11) NOT NULL, `action_description` longtext, `resolution_summary` longtext, `community_id` int(11) DEFAULT NULL, `op_impact_description` text, `zulu_date_time_out` datetime DEFAULT NULL, `zulu_date_time_in` datetime DEFAULT NULL, `outage_duration` float DEFAULT NULL, `request_source_id` int(11) DEFAULT NULL, `zulu_monitor_status_start` datetime DEFAULT NULL, `zulu_monitor_status_stop` datetime DEFAULT NULL, `zulu_date_time_etr` datetime DEFAULT NULL, `validation_source_id` int(11) DEFAULT NULL, `element_type_id` int(11) DEFAULT NULL, `element_id` tinytext, `validated` tinyint(1) DEFAULT NULL, `hit_si` varchar(255) DEFAULT NULL, `platform_domain_id` int(11) DEFAULT NULL, `action_type_id` int(11) DEFAULT NULL, `priority_id` int(11) DEFAULT NULL, `service1_id` int(11) DEFAULT NULL, `service2_id` int(11) DEFAULT NULL, `service3_id` int(11) DEFAULT NULL, `submitter_site_id` int(11) DEFAULT NULL, `supporting_site1_id` int(11) DEFAULT NULL, `supporting_site2_id` int(11) DEFAULT NULL, `assigned_group_id` int(11) DEFAULT NULL, `assigned_technician_id` int(11) DEFAULT NULL, `on_call_pool` varchar(255) DEFAULT NULL, PRIMARY KEY (`action_info_id`), KEY `impacted_community_id` (`community_id`), KEY `request_source_id` (`request_source_id`), KEY `validation_source_id` (`validation_source_id`), KEY `platform_domain_id` (`platform_domain_id`), KEY `priority_id` (`priority_id`), KEY `service1_id` (`service1_id`), KEY `service2_id` (`service2_id`), KEY `service3_id` (`service3_id`), KEY `submitter_site_id` (`submitter_site_id`), KEY `supporting_site1_id` (`supporting_site1_id`), KEY `supporting_site2_id` (`supporting_site2_id`), KEY `assigned_group_id` (`assigned_group_id`), KEY `assigned_technician_id` (`assigned_technician_id`), KEY `action_type_id` (`action_type_id`), KEY `ar_id` (`ar_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=60 ; -- -- Dumping data for table `meta_action_info` -- INSERT INTO `meta_action_info` (`action_info_id`, `ar_id`, `action_description`, `resolution_summary`, `community_id`, `op_impact_description`, `zulu_date_time_out`, `zulu_date_time_in`, `outage_duration`, `request_source_id`, `zulu_monitor_status_start`, `zulu_monitor_status_stop`, `zulu_date_time_etr`, `validation_source_id`, `element_type_id`, `element_id`, `validated`, `hit_si`, `platform_domain_id`, `action_type_id`, `priority_id`, `service1_id`, `service2_id`, `service3_id`, `submitter_site_id`, `supporting_site1_id`, `supporting_site2_id`, `assigned_group_id`, `assigned_technician_id`, `on_call_pool`) VALUES (2, 1, 'My name is <NAME> and I am having issues authenticating onto the mail.mil domain. My username is nwelch', 'This ticket is currently unresolved.', 1, 'TEST TICKET IMPACT DESCRIPTION', '2014-08-19 00:00:00', NULL, 2.31, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 1, 5, 1, 3, 3, 12, 12, 12, 5, NULL, NULL), (7, 7, 'ASI scheduled to upgrade the KIV-7M crypto on CCSD: HJB2.', '', 1, 'None', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 4, 4, 3, 3, 3, 14, 14, 14, 9, NULL, NULL), (9, 8, 'Our circuit is down. CCSD: 12RJ. It is a backup connection for DSN services. ', 'DSN NOC technicans are currenly working with the site.', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 2, 2, 3, 3, 3, 14, 12, 12, 17, NULL, NULL), (10, 9, 'Some phones in my office have been experiencing issues with their voicemail. We are in Bldg 1389', '', 1, '', NULL, NULL, NULL, 1, '2014-09-27 03:34:01', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 1, 1, 3, 3, 3, 13, 13, 13, 16, NULL, NULL), (11, 12, 'My name is <NAME> and I opened an invoice I received in an email as an attachment from one of the many vendors that support my office. My computer has been somewhat frozen ever since. ', '', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 1, 1, 3, 3, 3, 11, 11, 19, 8, NULL, NULL), (12, 13, 'My name is <NAME> and we are currently experiencing errors on Promina Node 15 CCSD:1289. We have a backup connection through CCSD: FJ1B and we are running a BERT test on the line to see why the errors are being experienced. ', '', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 2, 1, 3, 3, 3, 13, 13, 13, 13, NULL, NULL), (13, 14, 'I am currently experiencing problems with my computer. I am unable to log in. ', '', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 1, 1, 3, 3, 3, 11, 8, 8, 5, NULL, NULL), (14, 15, 'The switch in Bldg 1345 currently has no power. ', '', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 1, 1, 3, 3, 3, 8, 8, 8, 17, NULL, NULL), (15, 16, 'Users in 3115 are without network connectivity. ', 'Service has been restored however awaiting resolution from technician. ', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 1, 1, 3, 3, 3, 12, 12, 12, 5, NULL, NULL), (16, 17, 'There is a loud alarm coming from the main air cooler in our office. ', '', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 1, 1, 3, 3, 3, 12, 12, 12, 5, NULL, NULL), (17, 18, 'Circuit 12EE is currently down on SIPRNet. ', '', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 2, 2, 3, 3, 3, 14, 12, 12, 6, NULL, NULL), (18, 20, 'Kelly AFB ATM Lightstream switch is experiencing an issue with a pvc connection to Buckley AFB', '', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 2, 2, 3, 3, 3, 14, 12, 12, 17, NULL, NULL), (19, 21, 'Mildenhall ATM circuit 12DD is currently dropping packets. ', '', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 2, 2, 3, 3, 3, 16, 12, 16, 6, NULL, NULL), (20, 22, 'We are unable to get our backup ATM pvc connections backup after power outage. We are currently using our primary connection. ', '', 1, '', NULL, NULL, NULL, NULL, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', NULL, NULL, '', NULL, NULL, NULL, 2, 2, NULL, NULL, NULL, 8, 8, 8, 17, NULL, NULL), (21, 23, 'We provide SIPRNet service to a downrange node at Incirlik AB however our HAIPE is no longer communicating with their HAIPE. I can be reached at <EMAIL>', '', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 1, 5, 3, 3, 3, 9, 9, 9, 19, NULL, NULL), (22, 24, 'Incirlik AB is currently isolated from SIPRNet access and the only means for secure comms is through STE-III. I can be reached at <EMAIL> (DCCC)', '', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 2, 2, 3, 3, 3, 8, 8, 8, 17, NULL, NULL), (23, 25, 'I am unable to access my HARMONIEWeb sites. I am currently supporting OPERATION STANDUP and I need access. I am currently working at LAAFB and I can be reached at <EMAIL>', '', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 1, 1, 1, 3, 3, 11, 11, 13, 5, NULL, NULL), (24, 26, 'Unable to access DISA portal website (HARMONIEWeb). Everytime I try to go to the site my browser never loads and after a few minutes it crashes. I am at Mildenhall AFB and I can be reached at <EMAIL>', '', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 2, 3, 3, 3, 3, 48, 48, 48, 8, NULL, NULL), (25, 27, 'Last night I updated some files onto my HARMONIEWeb portal page however today I am unable to access my site. I was given administrative priviledges to upload documents but now my browser just sites there trying to load the page. I am at Ft. Belvoir, VA but the portal admin (<NAME>) can be reached at <EMAIL>', '', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 1, 1, 1, 3, 3, 40, 40, 40, 5, NULL, NULL), (26, 28, 'Multiple users in Bldg 313 are experiencing issues accessing the Internet. We require access to perform our daily duties. ', '', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 1, 4, 3, 3, 3, 13, 13, 13, 9, NULL, NULL), (27, 29, 'ASI scheduled for Promina Node 64 at Kelly AFB to replace HSD-2 card. This circuit provides services to an Intel detachment unit at Kelly. ', '', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 4, 1, 3, 3, 3, 14, 14, 14, 9, NULL, NULL), (28, 30, 'I have been unable to complete my security awareness training. Once I click on the link to verify my information, the page redirects me but never loads. ', '', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 1, 5, 3, 3, 3, 11, 11, 11, 4, NULL, NULL), (29, 31, 'Members in my office have received a few emails from users from these domains: w3kby.com and hz10.com over the course of the last two days. We are not familiar with either of these domains or the people. I can be reached at DSN 830-4456 and my name is <NAME>. ', '', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 1, 5, 3, 3, 3, 13, 13, 13, 4, NULL, NULL), (30, 32, 'I have been unable to complete the annual security awareness training sent out by the IAO. When I click on the link provided in the email the page never loads. I am unable to verify and submit my account information due to this issue. ', '', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 1, 5, 3, 3, 3, 13, 13, 13, 4, NULL, NULL), (31, 33, 'Primary DSN switch is still operational however it is saturated. Need to request increase in bandwidth to provide access for growth of users. ', '', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 2, 5, 3, 3, 3, 51, 51, 51, 16, NULL, NULL), (32, 34, 'We are experiencing errors on Promina Node 15. We have a backup node that provides us our T-3 service. We are running a BERT test on the line to see why the errors are being experienced. ', '', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 1, 5, 3, 3, 3, 49, 49, 49, 13, NULL, NULL), (33, 35, 'Our primary KG-175D is currently down due to faulty hardware. Currently using backup HAIPE. ', '', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 2, 5, 3, 3, 3, 26, 26, 54, 5, NULL, NULL), (34, 36, 'CCSD: 13FG is down due to poor satellite signal. ', '', NULL, '', NULL, NULL, NULL, NULL, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', NULL, NULL, '', NULL, NULL, NULL, 1, 5, NULL, NULL, NULL, 56, 56, 56, 5, NULL, NULL), (35, 37, 'CCSD: 33RT is down due to poor satellite visability. We have bad weather in our region. We are currently operational on our backup path. ', '', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 1, 5, 3, 3, 3, 52, 52, 52, 5, NULL, NULL), (36, 38, 'Commercial service provider is updating core PE router operating system. Services will be switched over to the backup during the 1 hour period being requested. ', '', 1, '', NULL, NULL, NULL, NULL, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, NULL, '', NULL, NULL, NULL, 4, NULL, NULL, NULL, NULL, 13, 13, 13, 9, NULL, NULL), (37, 39, 'ASI scheduled. We are decommissioning our T-1 circuits at our site. This will require us to take down multiple circuits. End users have been notified. No mission elements will be affected. ', '', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 1, 1, 1, 3, 3, 13, 13, 44, 9, NULL, NULL), (38, 40, 'I am unable to access the internal DISA-PAC Sharepoint', 'User was trying to access an unauthorized site. Access has been granted. ', 1, '', NULL, NULL, NULL, NULL, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, NULL, '', NULL, NULL, NULL, 1, 5, 1, NULL, NULL, 11, 11, 11, 5, NULL, NULL), (39, 41, 'CCSD: JKH3 on Promina Node 176 is down due to faulty wiring. ', 'Tech control personnel replaced wiring to Promina card. Circuit is back up and operational ', 1, '', NULL, NULL, NULL, NULL, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', NULL, NULL, '', NULL, NULL, NULL, 2, NULL, NULL, NULL, NULL, 52, 52, 52, 13, NULL, NULL), (40, 42, 'We are unable to make VoSIP calls to the following DSN prefixes: 240, 334, and 820', 'Updated Call Manager to reflect new confiuration for DSN prefixes\n', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 2, 3, 3, 3, 3, 48, 48, 48, 8, NULL, NULL), (41, 43, 'Circuit KKL4 is down due to emergency maintenance that had to be done to the Cell Xpress Card on Promina Node 33', 'Card had to be reseated to eliminated errors', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 1, 5, 1, 3, 3, 41, 41, 41, 13, NULL, NULL), (42, 11, 'My telephone is not receiving any phone calls. I am able to make phone calls but can not receive incoming calls. ', '', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 1, 1, 3, 3, 3, 11, 11, 19, 8, NULL, NULL), (44, 44, 'My name is <NAME> and I am requesting web-based access to SIPRNet. ', '', NULL, '', NULL, NULL, NULL, NULL, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', NULL, NULL, '', NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL, 40, 40, 40, 5, NULL, NULL), (45, 45, 'We are unable to connect to the weekly C4 VTC on our Tanberg terminal. ', '', NULL, '', NULL, NULL, NULL, NULL, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, NULL, '', NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL, 19, NULL, NULL, 16, NULL, NULL), (46, 46, 'We currently do not have VoSIP access. Please assist in troubleshooting this issue. ', '', NULL, '', NULL, NULL, NULL, NULL, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', NULL, NULL, '', NULL, NULL, NULL, 2, NULL, NULL, NULL, NULL, 56, 56, 56, 5, NULL, NULL), (47, 47, 'Circuit 14HJ is down due to a faulty card onour Promina node. It provides services to remote users however they are not running operations. ', 'Promina HSD Card was replaced and reseated. Circuit is back up and operational. ', 1, '', NULL, NULL, NULL, NULL, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, NULL, '', NULL, NULL, NULL, 2, NULL, NULL, NULL, NULL, 10, 10, 10, 13, NULL, NULL), (48, 48, 'The Cisco router supporting 89AA is down after we experienced a power outage. ', 'Technicians are currently replacing router with backup', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 2, 5, 1, 3, 3, 18, 18, 12, 13, NULL, NULL), (49, 49, 'I am unable to access my VPN connection at Kirtland AFB. ', '', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 2, 5, 1, 3, 3, 28, 28, 28, 17, NULL, NULL), (50, 50, 'Unable to dial out on my DSN line. My number is DSN 655-1254', 'Phone switch was reset. ', 1, '', NULL, NULL, NULL, NULL, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, NULL, '', NULL, NULL, NULL, 2, NULL, NULL, NULL, NULL, 7, 7, 7, 16, NULL, NULL), (51, 51, 'My account needs to be reset. My username is : <EMAIL>', '', NULL, '', NULL, NULL, NULL, NULL, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', NULL, NULL, '', NULL, NULL, NULL, 1, 5, NULL, NULL, NULL, 12, 12, 12, 5, NULL, NULL), (52, 52, 'I am unable to log into my SIPRNet terminal. My username is k.love', '', 1, '', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 1, 5, 1, 3, 3, 11, 11, 11, 5, NULL, NULL), (53, 53, 'My DSN line is not working. I am unable to contact remote users for OPERATION GOODHEART ', '', 1, '', NULL, NULL, NULL, NULL, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', NULL, NULL, '', NULL, NULL, NULL, 2, NULL, NULL, NULL, NULL, 12, 12, NULL, 5, NULL, NULL), (54, 54, 'I am unable to connect to SIPRNet with my SME-PED. ', '', 1, '', NULL, NULL, NULL, NULL, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, NULL, '', NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL, 25, 25, NULL, 5, NULL, NULL), (55, 55, 'We currently do not have NIPRNet acces at our location; FOB Camp Bush', 'A route was missing from upstream router that prevented traffic from being passed. ', 1, '', NULL, NULL, NULL, NULL, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, NULL, '', NULL, NULL, NULL, 2, NULL, NULL, NULL, NULL, 12, 12, NULL, 17, NULL, NULL), (56, 56, 'tesnth', 'tsah', 1, 'tn', NULL, NULL, NULL, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, 1, '', NULL, NULL, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, NULL); -- -------------------------------------------------------- -- -- Table structure for table `meta_action_requests` -- CREATE TABLE IF NOT EXISTS `meta_action_requests` ( `ar_id` int(11) NOT NULL AUTO_INCREMENT, `ar_number` varchar(25) NOT NULL, `action_type_id` int(11) DEFAULT NULL, `assigned_group_id` int(11) DEFAULT NULL, `status_id` int(11) DEFAULT NULL, `high_level_outage` varchar(255) DEFAULT NULL, `low_level_outage` varchar(255) DEFAULT NULL, `submitter_id` int(11) DEFAULT NULL, `quicket_id` int(11) DEFAULT NULL, `classification_id` int(11) DEFAULT NULL, `ar_delete` tinyint(1) DEFAULT '0', `description` text, PRIMARY KEY (`ar_id`), KEY `ar_group` (`assigned_group_id`), KEY `status` (`status_id`), KEY `submiter` (`submitter_id`), KEY `quicket_type` (`quicket_id`), KEY `classification` (`classification_id`), KEY `action_type_id` (`action_type_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=58 ; -- -- Dumping data for table `meta_action_requests` -- INSERT INTO `meta_action_requests` (`ar_id`, `ar_number`, `action_type_id`, `assigned_group_id`, `status_id`, `high_level_outage`, `low_level_outage`, `submitter_id`, `quicket_id`, `classification_id`, `ar_delete`, `description`) VALUES (1, 'WE K-00000001', 1, 5, 1, 'High Level Outage', 'Low Level Outage', 1, 2, 1, 0, 'My name is <NAME> and I am having issues authenticating onto the mail.mil domain. My username is nwelch'), (7, 'WE K-00000003', 4, 9, 4, 'N/A', 'N/A', 1, 1, 1, 0, 'ASI scheduled to upgrade the KIV-7M crypto on CCSD: HJB2.'), (8, 'WE K-00000004', 2, 17, 1, 'N/A', 'N/A', 1, 1, 1, 0, 'Our circuit is down. CCSD: 12RJ. It is a backup connection for DSN services. '), (9, 'WE K-00000005', 1, 16, 3, 'N/A', 'N/A', 1, 1, 1, 0, 'Some phones in my office have been experiencing issues with their voicemail. We are in Bldg 1389'), (11, 'WE K-00000006', 1, 8, 3, 'N/A', 'N/A', 1, 1, 1, 0, 'My telephone is not receiving any phone calls. I am able to make phone calls but can not receive incoming calls. '), (12, 'WE K-00000007', 1, 8, 3, 'N/A', 'N/A', 1, 1, 1, 0, 'My name is <NAME> and I opened an invoice I received in an email as an attachment from one of the many vendors that support my office. My computer has been somewhat frozen ever since. '), (13, 'WE K-00000008', 2, 13, 1, 'N/A', 'N/A', 1, 1, 1, 0, 'My name is <NAME> and we are currently experiencing errors on Promina Node 15 CCSD:1289. We have a backup connection through CCSD: FJ1B and we are running a BERT test on the line to see why the errors are being experienced. '), (14, 'WE K-00000009', 1, 5, 3, 'N/A', 'N/A', 1, 1, 1, 0, 'I am currently experiencing problems with my computer. I am unable to log in. '), (15, 'WE K-00000010', 1, 17, 1, 'N/A', 'N/A', 1, 1, 1, 0, 'The switch in Bldg 1345 currently has no power. '), (16, 'WE K-000000011', 1, 5, 4, 'N/A', 'N/A', 1, 1, 1, 0, 'Users in 3115 are without network connectivity. '), (17, 'WE K-00000012', 1, 5, 3, 'N/A', 'N/A', 1, 1, 1, 0, 'There is a loud alarm coming from the main air cooler in our office. '), (18, 'WE K-00000013', 2, 6, 1, 'N/A', 'N/A', 1, 1, 1, 0, 'Circuit 12EE is currently down on SIPRNet. '), (20, 'WE K-00000014', 2, 17, 1, 'N/A', 'N/A', 1, 1, 1, 0, 'Kelly AFB ATM Lightstream switch is experiencing an issue with a pvc connection to Buckley AFB'), (21, 'WE K-00000015', 2, 6, 1, 'N/A', 'N/A', 1, 1, 1, 0, 'Mildenhall ATM circuit 12DD is currently dropping packets. '), (22, 'WE K-00000016', 2, 17, 3, 'N/A', 'N/A', 1, 2, 1, 0, 'We are unable to get our backup ATM pvc connections backup after power outage. We are currently using our primary connection. '), (23, 'WE K-00000017', 1, 19, 3, 'N/A', 'N/A', 1, 2, 1, 0, 'We provide SIPRNet service to a downrange node at Incirlik AB however our HAIPE is no longer communicating with their HAIPE. I can be reached at <EMAIL>'), (24, 'WE K-00000018', 2, 17, 3, 'N/A', 'N/A', 1, 2, 1, 0, 'Incirlik AB is currently isolated from SIPRNet access and the only means for secure comms is through STE-III. I can be reached at <EMAIL> (DCCC)'), (25, 'WE K-00000019', 1, 5, 3, 'N/A', 'N/A', 1, 1, 1, 0, 'I am unable to access my HARMONIEWeb sites. I am currently supporting OPERATION STANDUP and I need access. I am currently working at LAAFB and I can be reached at <EMAIL>'), (26, 'WE K-00000020', 2, 8, 2, 'N/A', 'N/A', 1, 1, 1, 0, 'Unable to access DISA portal website (HARMONIEWeb). Everytime I try to go to the site my browser never loads and after a few minutes it crashes. I am at Mildenhall AFB and I can be reached at <EMAIL>'), (27, 'WE K-00000021', 1, 5, 3, 'N/A', 'N/A', 1, 1, NULL, 0, 'Last night I updated some files onto my HARMONIEWeb portal page however today I am unable to access my site. I was given administrative priviledges to upload documents but now my browser just sites there trying to load the page. I am at Ft. Belvoir, VA but the portal admin (<NAME>) can be reached at <EMAIL>'), (28, 'WE K-00000022', 1, 9, 3, 'N/A', 'N/A', 1, 2, 1, 0, 'Multiple users in Bldg 313 are experiencing issues accessing the Internet. We require access to perform our daily duties. '), (29, 'WE K-00000023', 4, 9, 4, 'N/A', 'N/A', 1, 2, 1, 0, 'ASI scheduled for Promina Node 64 at Kelly AFB to replace HSD-2 card. This circuit provides services to an Intel detachment unit at Kelly. '), (30, 'WE K-00000024', 1, 5, 3, 'N/A', 'N/A', 1, 2, 1, 0, 'I have been unable to complete my security awareness training. Once I click on the link to verify my information, the page redirects me but never loads. '), (31, 'WE K-00000025', 1, 4, 3, 'N/A', 'N/A', 1, 2, 1, 0, 'Members in my office have received a few emails from users from these domains: w3kby.com and hz10.com over the course of the last two days. We are not familiar with either of these domains or the people. I can be reached at DSN 830-4456 and my name is <NAME>. '), (32, 'WE K-00000026', 1, 4, 3, 'N/A', 'N/A', 1, 2, 1, 0, 'I have been unable to complete the annual security awareness training sent out by the IAO. When I click on the link provided in the email the page never loads. I am unable to verify and submit my account information due to this issue. '), (33, 'WE K-00000027', 2, 16, 3, '', '', NULL, 2, 1, 0, 'Primary DSN switch is still operational however it is saturated. Need to request increase in bandwidth to provide access for growth of users. '), (34, 'WE K-00000028', 1, 13, 3, '', '', NULL, 1, 1, 0, 'We are experiencing errors on Promina Node 15. We have a backup node that provides us our T-3 service. We are running a BERT test on the line to see why the errors are being experienced. '), (35, 'WE K-00000029', 2, 5, 3, '', '', NULL, 1, 1, 0, 'Our primary KG-175D is currently down due to faulty hardware. Currently using backup HAIPE. '), (36, 'WE K-00000030', 1, 5, 3, '', '', NULL, NULL, 1, 0, 'CCSD: 13FG is down due to poor satellite signal. '), (37, 'WE K-00000031', 1, 5, 3, '', '', NULL, 1, 1, 0, 'CCSD: 33RT is down due to poor satellite visability. We have bad weather in our region. We are currently operational on our backup path. '), (38, 'WE K-00000032', 4, 9, 3, 'H/A', 'H/A', 1, 2, 1, 0, 'Commercial service provider is updating core PE router operating system. Services will be switched over to the backup during the 1 hour period being requested. '), (39, 'WE K-00000033', 1, 9, 3, 'N/A', 'N/A', 1, 1, 1, 0, 'ASI scheduled. We are decommissioning our T-1 circuits at our site. This will require us to take down multiple circuits. End users have been notified. No mission elements will be affected. '), (40, 'WE K-00000034', 1, 5, 2, 'N/A', 'N/A', 1, 2, 1, 0, 'I am unable to access the internal DISA-PAC Sharepoint'), (41, 'WE K-00000035', 2, 13, 2, 'N/A', 'N/A', 1, 2, 1, 0, 'CCSD: JKH3 on Promina Node 176 is down due to faulty wiring. '), (42, 'WE K-00000036', 2, 8, 2, '', '', NULL, 1, 1, 0, 'We are unable to make VoSIP calls to the following DSN prefixes: 240, 334, and 820'), (43, 'WE K-00000037', 1, 13, 2, '', '', NULL, 2, 1, 0, 'Circuit KKL4 is down due to emergency maintenance that had to be done to the Cell Xpress Card on Promina Node 33'), (44, 'WE K-00000038', 1, 5, 3, 'N/A', 'N/A', 1, NULL, NULL, 0, 'My name is <NAME> and I am requesting web-based access to SIPRNet. '), (45, 'WE K-00000039', 1, 16, 1, '', '', NULL, NULL, NULL, 0, 'We are unable to connect to the weekly C4 VTC on our Tanberg terminal. '), (46, 'WE K-000000310', 2, 5, 3, '', '', 1, NULL, NULL, 0, 'We currently do not have VoSIP access. Please assist in troubleshooting this issue. '), (47, 'WE K-000000311', 2, 13, 2, '', '', NULL, NULL, NULL, 0, 'Circuit 14HJ is down due to a faulty card onour Promina node. It provides services to remote users however they are not running operations. '), (48, 'WE K-000000312', 2, 13, 1, '', '', 1, 2, 1, 0, 'The Cisco router supporting 89AA is down after we experienced a power outage. '), (49, 'WE K-000000313', 2, 17, 3, '', '', 1, 2, 1, 0, 'I am unable to access my VPN connection at Kirtland AFB. '), (50, 'WE K-000000314', 2, 16, 2, '', '', NULL, NULL, 1, 0, 'Unable to dial out on my DSN line. My number is DSN 655-1254'), (51, 'WE K-000000315', 1, 5, 3, '', '', 1, 2, 1, 0, 'My account needs to be reset. My username is : <EMAIL>'), (52, 'WE K-000000316', 1, 5, 3, '', '', 1, 2, 1, 0, 'I am unable to log into my SIPRNet terminal. My username is k.love'), (53, 'WE K-000000317', 2, 5, 3, '', '', NULL, NULL, 1, 0, 'My DSN line is not working. I am unable to contact remote users for OPERATION GOODHEART '), (54, 'WE K-000000318', 1, 5, 3, '', '', 1, NULL, NULL, 0, 'I am unable to connect to SIPRNet with my SME-PED. '), (55, 'WE K-000000319', 2, 17, 2, '', '', 1, 2, 1, 0, 'We currently do not have NIPRNet acces at our location; FOB Camp Bush'), (56, 'WE K-0000003110', 1, 1, 1, 'ste', 'st', 1, 1, 1, 0, 'tesnth'), (57, 'WE K-0000003110', 1, 1, 1, 'ste', 'st', 1, 1, 1, 0, 'tesnth'); -- -------------------------------------------------------- -- -- Table structure for table `meta_fault_summary` -- CREATE TABLE IF NOT EXISTS `meta_fault_summary` ( `fault_id` int(11) NOT NULL AUTO_INCREMENT, `ar_id` int(11) NOT NULL, `fault_date_time_out` datetime DEFAULT NULL, `fault_date_time_in` datetime DEFAULT NULL, `service4_id` int(11) DEFAULT NULL, `fault_duration` decimal(10,0) DEFAULT NULL, `fault_location_id` int(11) DEFAULT NULL, `fault_category_id` int(11) DEFAULT NULL, `rfo1_id` int(11) DEFAULT NULL, `rfo2_id` int(11) DEFAULT NULL, `vendor_id` int(11) DEFAULT NULL, `vendor_ticket_number` tinytext, `rfo_remarks` text, PRIMARY KEY (`fault_id`), KEY `ar_id` (`ar_id`), KEY `service4_id` (`service4_id`), KEY `fault_location_id` (`fault_location_id`), KEY `fault_category_id` (`fault_category_id`), KEY `rfo1_id` (`rfo1_id`), KEY `rfo2_id` (`rfo2_id`), KEY `vendor_id` (`vendor_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=51 ; -- -- Dumping data for table `meta_fault_summary` -- INSERT INTO `meta_fault_summary` (`fault_id`, `ar_id`, `fault_date_time_out`, `fault_date_time_in`, `service4_id`, `fault_duration`, `fault_location_id`, `fault_category_id`, `rfo1_id`, `rfo2_id`, `vendor_id`, `vendor_ticket_number`, `rfo_remarks`) VALUES (1, 1, '2014-08-20 00:00:00', NULL, 3, 3, 12, 1, 1, 1, 1, '', 'Reason for outage was due to failing PSU in DC.'), (3, 7, '0000-00-00 00:00:00', NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (4, 8, '0000-00-00 00:00:00', NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (5, 9, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (6, 12, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (7, 13, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (8, 14, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (9, 15, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (10, 16, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (11, 17, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (12, 18, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (13, 20, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (14, 21, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (15, 22, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '', ''), (16, 23, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (17, 24, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (18, 25, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (19, 26, NULL, NULL, 3, NULL, 16, 1, 1, 1, 1, '', ''), (20, 27, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (21, 28, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (22, 29, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (23, 30, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (24, 31, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (25, 32, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (26, 33, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (27, 34, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (28, 35, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (29, 36, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '', ''), (30, 37, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (31, 38, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '', ''), (32, 39, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (33, 40, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '', ''), (34, 41, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '', ''), (35, 42, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (36, 43, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (37, 11, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (38, 44, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '', ''), (39, 45, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '', ''), (40, 46, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '', ''), (41, 47, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '', ''), (42, 48, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (43, 49, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (44, 50, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '', ''), (45, 51, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '', ''), (46, 52, NULL, NULL, 3, NULL, 17, 1, 1, 1, 1, '', ''), (47, 53, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '', ''), (48, 54, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '', ''), (49, 55, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '', ''), (50, 56, NULL, NULL, 1, NULL, 1, 2, 1, 1, 1, '', 'aoeu'); -- -------------------------------------------------------- -- -- Table structure for table `platform` -- CREATE TABLE IF NOT EXISTS `platform` ( `platform_id` int(11) NOT NULL AUTO_INCREMENT, `platform_description` tinytext NOT NULL, PRIMARY KEY (`platform_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; -- -- Dumping data for table `platform` -- INSERT INTO `platform` (`platform_id`, `platform_description`) VALUES (1, 'Test Platform'); -- -------------------------------------------------------- -- -- Table structure for table `priority` -- CREATE TABLE IF NOT EXISTS `priority` ( `priority_id` int(11) NOT NULL AUTO_INCREMENT, `priority_description` tinytext NOT NULL, PRIMARY KEY (`priority_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ; -- -- Dumping data for table `priority` -- INSERT INTO `priority` (`priority_id`, `priority_description`) VALUES (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'); -- -------------------------------------------------------- -- -- Table structure for table `quicket` -- CREATE TABLE IF NOT EXISTS `quicket` ( `quicket_id` int(11) NOT NULL AUTO_INCREMENT, `quicket_description` tinytext NOT NULL, PRIMARY KEY (`quicket_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ; -- -- Dumping data for table `quicket` -- INSERT INTO `quicket` (`quicket_id`, `quicket_description`) VALUES (1, 'Test Quicket'), (2, 'QUICKET 1'), (3, 'QUICKET 2'), (4, 'QUICKET 3'), (5, 'QUICKET 4'); -- -------------------------------------------------------- -- -- Table structure for table `rfo` -- CREATE TABLE IF NOT EXISTS `rfo` ( `rfo_id` int(11) NOT NULL AUTO_INCREMENT, `rfo_description` tinytext NOT NULL, PRIMARY KEY (`rfo_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ; -- -- Dumping data for table `rfo` -- INSERT INTO `rfo` (`rfo_id`, `rfo_description`) VALUES (1, 'RFO 1'), (2, 'RFO 2'), (3, 'RFO 3'), (4, 'RFO 4'); -- -------------------------------------------------------- -- -- Table structure for table `service` -- CREATE TABLE IF NOT EXISTS `service` ( `service_id` int(11) NOT NULL AUTO_INCREMENT, `service_description` tinytext NOT NULL, PRIMARY KEY (`service_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ; -- -- Dumping data for table `service` -- INSERT INTO `service` (`service_id`, `service_description`) VALUES (1, 'COMPUTING'), (2, 'OTHER CUSTOMER SUPPORT'), (3, 'MISCELLANEOUS'), (4, 'APPLICATIONS'), (5, 'DMS-BLACK'); -- -------------------------------------------------------- -- -- Table structure for table `site` -- CREATE TABLE IF NOT EXISTS `site` ( `site_id` int(11) NOT NULL AUTO_INCREMENT, `site_description` tinytext NOT NULL, PRIMARY KEY (`site_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=58 ; -- -- Dumping data for table `site` -- INSERT INTO `site` (`site_id`, `site_description`) VALUES (1, 'DISA CS MO TECH SUPPORT'), (2, 'SMC-TECH SPT'), (3, 'MONTGOMERY'), (4, 'GNC DCTS NOC'), (5, 'TNC'), (6, 'PAC'), (7, 'Ft. Belvoir'), (8, 'Hickam'), (9, '<NAME>'), (10, 'Beale'), (11, 'DISA-PAC'), (12, 'DISA-EUR'), (13, 'DISA-CONUS'), (14, 'Kelly'), (15, 'Incirlik'), (16, 'Mildenhall'), (17, 'LAAFB'), (18, 'Ft. Shafter'), (19, 'Kadena'), (20, 'Other'), (21, 'DISA HQ'), (22, 'DECC'), (23, 'Ft. Greely'), (24, 'VAFB'), (25, 'Shriever'), (26, '<NAME>'), (27, 'Thule'), (28, 'Bolling'), (29, 'Andrews'), (30, 'Ft. Detrick'), (31, 'Onizuka'), (32, 'Hill'), (33, 'Barksdale'), (34, '<NAME>'), (35, 'Dobbins'), (36, 'Ft. Gordon'), (37, 'Manta'), (38, '<NAME>'), (39, '<NAME>'), (40, 'Ponce'), (41, 'Ft. Lewis'), (42, 'Rota'), (43, 'Moron'), (44, 'Pristina'), (45, 'Aviano'), (46, 'Ramstein'), (47, '<NAME>'), (48, 'Heidelberg'), (49, 'Butmir'), (50, 'Shape'), (51, 'Horn of Africa'), (52, 'Osan'), (53, 'Andersen'), (54, '<NAME>'), (55, 'Kunsan'), (56, 'Sasebo'), (57, 'lzmir'); -- -------------------------------------------------------- -- -- Table structure for table `source` -- CREATE TABLE IF NOT EXISTS `source` ( `source_id` int(11) NOT NULL AUTO_INCREMENT, `source_description` tinytext NOT NULL, PRIMARY KEY (`source_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; -- -- Dumping data for table `source` -- INSERT INTO `source` (`source_id`, `source_description`) VALUES (1, 'Test Source 1'), (2, 'Test Source 2'); -- -------------------------------------------------------- -- -- Table structure for table `status` -- CREATE TABLE IF NOT EXISTS `status` ( `status_id` int(11) NOT NULL AUTO_INCREMENT, `status_description` tinytext NOT NULL, PRIMARY KEY (`status_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ; -- -- Dumping data for table `status` -- INSERT INTO `status` (`status_id`, `status_description`) VALUES (1, 'IN PROGRESS'), (2, 'CLOSED'), (3, 'OPEN'), (4, 'PENDING'); -- -------------------------------------------------------- -- -- Table structure for table `summary` -- CREATE TABLE IF NOT EXISTS `summary` ( `summary_id` int(11) NOT NULL AUTO_INCREMENT, `summary_description` text NOT NULL, PRIMARY KEY (`summary_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; -- -- Dumping data for table `summary` -- INSERT INTO `summary` (`summary_id`, `summary_description`) VALUES (1, 'This is a test of the summary field.'), (2, 'This is another test of the summary field.'); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE IF NOT EXISTS `users` ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `username` tinytext NOT NULL, `password` tinytext NOT NULL, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; -- -- Dumping data for table `users` -- INSERT INTO `users` (`user_id`, `username`, `password`) VALUES (1, 'REMEDY', '<PASSWORD>'), (2, 'user1', '<PASSWORD>'); -- -------------------------------------------------------- -- -- Table structure for table `vendor` -- CREATE TABLE IF NOT EXISTS `vendor` ( `vendor_id` int(11) NOT NULL AUTO_INCREMENT, `vendor_description` tinytext NOT NULL, PRIMARY KEY (`vendor_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ; -- -- Dumping data for table `vendor` -- INSERT INTO `vendor` (`vendor_id`, `vendor_description`) VALUES (1, 'Vendor 1'), (2, 'Vendor 2'), (3, 'Vendor 3'), (4, 'Vendor 4'); -- -- Constraints for dumped tables -- -- -- Constraints for table `meta_action_info` -- ALTER TABLE `meta_action_info` ADD CONSTRAINT `meta_action_info_ibfk_1` FOREIGN KEY (`community_id`) REFERENCES `community` (`community_id`), ADD CONSTRAINT `meta_action_info_ibfk_10` FOREIGN KEY (`service2_id`) REFERENCES `service` (`service_id`), ADD CONSTRAINT `meta_action_info_ibfk_11` FOREIGN KEY (`service3_id`) REFERENCES `service` (`service_id`), ADD CONSTRAINT `meta_action_info_ibfk_12` FOREIGN KEY (`supporting_site1_id`) REFERENCES `site` (`site_id`), ADD CONSTRAINT `meta_action_info_ibfk_13` FOREIGN KEY (`supporting_site2_id`) REFERENCES `site` (`site_id`), ADD CONSTRAINT `meta_action_info_ibfk_14` FOREIGN KEY (`assigned_group_id`) REFERENCES `assigned_group` (`assigned_group_id`), ADD CONSTRAINT `meta_action_info_ibfk_15` FOREIGN KEY (`ar_id`) REFERENCES `meta_action_requests` (`ar_id`), ADD CONSTRAINT `meta_action_info_ibfk_2` FOREIGN KEY (`request_source_id`) REFERENCES `source` (`source_id`), ADD CONSTRAINT `meta_action_info_ibfk_3` FOREIGN KEY (`platform_domain_id`) REFERENCES `platform` (`platform_id`), ADD CONSTRAINT `meta_action_info_ibfk_4` FOREIGN KEY (`action_type_id`) REFERENCES `action_type` (`action_type_id`), ADD CONSTRAINT `meta_action_info_ibfk_5` FOREIGN KEY (`priority_id`) REFERENCES `priority` (`priority_id`), ADD CONSTRAINT `meta_action_info_ibfk_6` FOREIGN KEY (`service1_id`) REFERENCES `service` (`service_id`), ADD CONSTRAINT `meta_action_info_ibfk_7` FOREIGN KEY (`submitter_site_id`) REFERENCES `site` (`site_id`), ADD CONSTRAINT `meta_action_info_ibfk_8` FOREIGN KEY (`assigned_technician_id`) REFERENCES `users` (`user_id`), ADD CONSTRAINT `meta_action_info_ibfk_9` FOREIGN KEY (`validation_source_id`) REFERENCES `source` (`source_id`); -- -- Constraints for table `meta_action_requests` -- ALTER TABLE `meta_action_requests` ADD CONSTRAINT `classification_description` FOREIGN KEY (`classification_id`) REFERENCES `classification` (`classification_id`), ADD CONSTRAINT `group_description` FOREIGN KEY (`assigned_group_id`) REFERENCES `assigned_group` (`assigned_group_id`), ADD CONSTRAINT `meta_action_requests_ibfk_2` FOREIGN KEY (`submitter_id`) REFERENCES `users` (`user_id`), ADD CONSTRAINT `meta_action_requests_ibfk_3` FOREIGN KEY (`action_type_id`) REFERENCES `action_type` (`action_type_id`), ADD CONSTRAINT `quicket_description` FOREIGN KEY (`quicket_id`) REFERENCES `quicket` (`quicket_id`), ADD CONSTRAINT `status_description` FOREIGN KEY (`status_id`) REFERENCES `status` (`status_id`); -- -- Constraints for table `meta_fault_summary` -- ALTER TABLE `meta_fault_summary` ADD CONSTRAINT `meta_fault_summary_ibfk_1` FOREIGN KEY (`ar_id`) REFERENCES `meta_action_requests` (`ar_id`), ADD CONSTRAINT `meta_fault_summary_ibfk_2` FOREIGN KEY (`service4_id`) REFERENCES `service` (`service_id`), ADD CONSTRAINT `meta_fault_summary_ibfk_3` FOREIGN KEY (`fault_location_id`) REFERENCES `site` (`site_id`), ADD CONSTRAINT `meta_fault_summary_ibfk_4` FOREIGN KEY (`fault_category_id`) REFERENCES `fault_category` (`fault_category_id`), ADD CONSTRAINT `meta_fault_summary_ibfk_5` FOREIGN KEY (`rfo1_id`) REFERENCES `rfo` (`rfo_id`), ADD CONSTRAINT `meta_fault_summary_ibfk_6` FOREIGN KEY (`rfo2_id`) REFERENCES `rfo` (`rfo_id`), ADD CONSTRAINT `meta_fault_summary_ibfk_7` FOREIGN KEY (`vendor_id`) REFERENCES `vendor` (`vendor_id`); /*!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 */; <file_sep>/ar_num_test.php <?php require_once("classes/class.database.php"); $db = new Database(); // We need to get the last inserted AR Nmuber and increment it by one. Since this is a alpha-numeric value // auto-increment won't work in this circumstance. We are making the assumption the tickets will be limited to // 8 place holders or less, meaning we are limited to 99,999,999 unique tickets. If this isn't enough, we should // probably consider refactoring this application. $ar_query = "SELECT ar_number FROM meta_action_requests ORDER BY ar_id DESC LIMIT 1"; $db->query($ar_query); $old_ar_num = $db->single(); $new_ar_num = substr($old_ar_num['ar_number'], 0, -8) . substr($old_ar_num['ar_number'], -8, -1) . (1+substr($old_ar_num['ar_number'], -1)); echo $new_ar_num; ?><file_sep>/js/new_ticket.js $(function() { $("#action_tab_container").tabs({ active: 1, activate: function() { selected_ar_tab = $("li.ui-tabs-active").children(":first").text(); } }); $("#details_tab_container").tabs({ activate: function() { selected_fault_tab = $("li.ui-tabs-active").children(":first").text(); } }); $("#update_ticket").on("click", function updateTicket() { var ar = new Object(); ar.action_type_id = $("select#action_type option:selected").val(); ar.status_id = $("select#status option:selected").val(); ar.high_level_outage = $("input#high_level_outage").val(); ar.low_level_outage = $("input#low_level_outage").val(); ar.submitter_id = $("select#submitter_id option:selected").val(); ar.quicket_id = $("select#quicket option:selected").val(); ar.classification_id = $("select#classification option:selected").val(); var action_info = new Object(); //action_info.ar_id = selected_ar; action_info.action_description = $("textarea#action_description_text").val(); action_info.resolution_summary = $("textarea#resolution_text").val(); action_info.community_id = $("select#community option:selected").val(); action_info.op_impact_description = $("input#op_impact").val(); action_info.request_source_id = $("select#request_source option:selected").val(); action_info.zulu_monitor_status_start = $("input#zulu_monitor_status_start").val(); action_info.zulu_monitor_status_stop = $("input#zulu_monitor_status_stop").val(); action_info.zulu_date_time_etr = $("input#zulu_date_time_etr").val(); action_info.validation_source_id = $("select#validation_source option:selected").val(); action_info.element_type_id = $("select#element_type option:selected").val(); action_info.element_id = $("input#element_id").val(); action_info.platform_domain_id = $("select#domain_platform option:selected").val(); action_info.action_type_id = $("select#action_type option:selected").val(); action_info.priority_id = $("select#priority option:selected").val(); action_info.service1_id = $("select#service1 option:selected").val(); action_info.service2_id = $("select#service2 option:selected").val(); action_info.service3_id = $("select#service3 option:selected").val(); action_info.submitter_site_id = $("select#submitter_site option:selected").val(); action_info.supporting_site1_id = $("select#supporting_site1 option:selected").val(); action_info.supporting_site2_id = $("select#supporting_site2 option:selected").val(); action_info.assigned_group_id = $("select#assigned_group option:selected").val(); action_info.assigned_technician_id = $("select#assigned_technician option:selected").val(); var fault = new Object(); //fault.ar_id = selected_ar; fault.fault_date_time_out = $("input#fault_date_time_out").val(); fault.zulu_date_time_id = $("input#fault_date_time_in").val(); fault.service4_id = $("select#service4 option:selected").val(); fault.fault_location_id = $("select#fault_location_id option:selected").val(); fault.fault_category_id = $("select#fault_category option:selected").val(); fault.rfo1_id = $("select#rfo1 option:selected").val(); fault.rfo2_id = $("select#rfo2 option:selected").val(); fault.vendor_id = $("select#vendor option:selected").val(); fault.vendor_ticket_number = $("input#vendor_ticket_number").val(); fault.rfo_remarks = $("input#rfo_remarks").val(); create_action_request(ar, action_info, fault); }); // Eventually this functions should only receive modified data, but currently only get all data from fields // these update functions will pass single variables (e.g., ar_id = 1, ar_number: xxx), this will allow // for only updating new data, and not assuming ALL fields have been passed to the API // IMPORTANT: This function will successfully create tickets regardless of the amount of tables, // but you MUST put the meta_action_table object first!!!!!!!!!!!!!!!!!!!!!! function create_action_request(ar, action_info, fault) { $.ajax({ type: "POST", url: "api/create_action_request.php", data: {meta_action_requests: ar, meta_action_info: action_info, meta_fault_summary: fault}, dataType: JSON, onSuccess: function() { $("input").val() = ""; } }); } });<file_sep>/template_engine.php <?php require_once("classes/class.database.php"); function getDropDown($table, $modifier = "", $id="") { $db = new Database(); $db->query(" SELECT * FROM " . $table); $results = $db->resultSet(); if($id !== "") { $drop_down_code = "<select id=" . $id . ">\n"; } else if($modifier !== "") { $drop_down_code = "<select id=" . $modifier . "_" . $table . ">\n"; } else{ $drop_down_code = "<select id=" . $table . ">\n"; } $drop_down_code .= " <option value=NULL>&nbsp;</option>\n"; if($table !== "users") { foreach ($results as $result) $drop_down_code .= " <option value=" . $result[$table . "_id"] . ">" . $result[$table . "_description"] . "</option>\n"; } else { foreach ($results as $result) $drop_down_code .= " <option value=" . $result["user_id"] . ">" . $result["username"] . "</option>\n"; } $drop_down_code .= "</select>\n"; return $drop_down_code; } ?><file_sep>/api/update_action_request.php <?php if(isset($_POST['ar_id'])) { require_once("../classes/class.database.php"); $db = new Database(); $ar_id = $_POST['ar_id']; $query = " UPDATE meta_action_requests SET "; $last_key = end(array_keys($_POST)); foreach($_POST as $key => $param) { $param = ($param == 'NULL') ? "NULL" : "'" . $param . "'"; $query .= "$key = $param"; $query .= ($key !== $last_key) ? ", " : " "; } $query .= "WHERE ar_id = '$ar_id';"; $db->query($query); $db->update(); } /* * This query doesn't utilize PDO BIND statements, due to the FOREACH loop, and is at risk of SQL injection. * Needs to be refactored with BIND statements at some point. */ ?><file_sep>/api/action_info.php <?php require_once("../classes/class.database.php"); if(isset($_GET['ar_id'])) { $db = new Database(); $db->query(" SELECT action_info_id, ar_id, action_description, resolution_summary, community_id, op_impact_description, zulu_date_time_out, zulu_date_time_in, outage_duration, request_source_id, zulu_monitor_status_start, zulu_monitor_status_stop, zulu_date_time_etr, validation_source_id, element_type_id, validated, hit_si, platform_domain_id, action_type_id, priority_id, service1_id, service2_id, service3_id, submitter_site_id, supporting_site1_id, supporting_site2_id, assigned_group_id, assigned_technician_id, on_call_pool FROM meta_action_info AS ai WHERE ar_id = :ar_id; "); $db->bind(":ar_id", $_GET['ar_id'], 3); $action_requests = $db->resultSet(); print_r(json_encode($action_requests)); } else { echo "Restricted"; } ?><file_sep>/js/search.js $(function() { var selected_ar; var selected_fault; var selected_ar_tab; var selected_fault_tab; var ar_data; $( "#tickets_container" ).resizable({ handles: 's', stop: function(event, ui) { $(this).css("width", ''); } }); $("#action_tab_container").tabs({ active: 1, activate: function() { selected_ar_tab = $("li.ui-tabs-active").children(":first").text(); } }); $("#details_tab_container").tabs({ activate: function() { selected_fault_tab = $("li.ui-tabs-active").children(":first").text(); } }); $(".flex1").flexigrid({ url:"api/ar_grid.php", dataType: "json", colModel: [ {display: "AR ID", name: "ar_id", hide:true}, {display: "AR Number", name: "ar_number", width:100, sortable:true}, {display: "Status", name: "status_description", width:100, sortable:true}, {display: "Group", name: "group_description", width:200}, {display: "Zulu Date Time Out", name: "zulu_date_time_out", width:130}, {display: "Action Type", name: "action_type_description", width:200}, {display: "Description", name: "description", width:247} ], sortname: "ar_id", sortorder: "asc", usepager: true, height: 100, useRp: true, rp:100, singleSelect: true, showToggleBtn: false, searchitems: [ {display: "AR Number", name: "ar_number", isdefault: true}, {display: "Status", name: "status_description"}, {display: "Group", name: "group_description"}, {display: "Zulu Date Time Out", name: "zulu_date_time_out"}, {display: "Action Type", name: "action_type_description"}, {display: "Description", name: "description"} ], onSuccess: function() { $("table.flex1 tr[id^='row'").on("click", function() { if(selected_ar !== $(this).children(":first").text()) { selected_ar = $(this).children(":first").text(); populate_ar_data(); } }); $("tr#row1").trigger("click"); } }); var fault_grid = $(".flex2").flexigrid({ url:"api/fault_grid.php", dataType: "json", colModel: [ {display: "AR ID", name: "ar_id", hide:true}, {display: "Zulu Date Time Out", name: "fault_date_time_out", width:100}, {display: "Zulu Date Time In", name: "fault_date_time_in", width:100}, {display: "Service 4", name: "service_description", width:100}, {display: "Fault Duration", name: "fault_duration", width:70}, {display: "Location of Problem", name: "site_description", width:100}, {display: "Fault Category", name: "fault_category_description", width:75}, {display: "RFO 1", name: "rfo1_description", width:50}, {display: "RFO 2", name: "rfo2_description", width:50}, {display: "Vendor", name: "vendor_description", width:50}, {display: "Vendor Ticket", name: "vendor_ticket_number", width:70}, {display: "RFO Remarks", name: "rfo_remarks", width:130} ], sortorder: "asc", height: 100, singleSelect: true, onSuccess: function(data) { $("table.flex2 tr[id^='row'").on("click", function(data) { selected_fault = $(this).children(":first").text(); }); } }); function populate_ar_data() { $.getJSON("api/action_requests.php?ar_id=" + selected_ar, function(response){ $("input#ar_number").val(response[0].ar_number); $("select#status option").each(function(){ if($(this).val()==response[0].status_id || !response[0].status_id) { $(this).attr("selected", "selected"); return false; } }); $("input#high_level_outage").val(response[0].high_level_outage); $("input#low_level_outage").val(response[0].low_level_outage); $("input#submitter").val(response[0].username); $("select#quicket option").each(function(){ if($(this).val() == response[0].quicket_id || !response[0].quicket_id) { $(this).attr("selected", "selected"); return false; } }); $("select#classification option").each(function(){ if($(this).val() == response[0].classification_id || !response[0].classification_id) { $(this).attr("selected", "selected"); return false; } }); selected_delete = response[0].ar_delete == 0 ? "no" : "yes"; $("select#delete option").each(function(){ if($(this).val()==selected_delete) $(this).attr("selected", "selected"); }); }); //This needs to not be called procedurally from this function populate_action_info_tab(); populate_fault_tab(); } function populate_action_info_tab() { $.getJSON("api/action_info.php?ar_id=" + selected_ar, function(response){ $("textarea#action_description_text").val(response[0].action_description); $("textarea#resolution_text").val(response[0].summary_description); $("select#community option").each(function(){ if($(this).val()==response[0].community_id) $(this).attr("selected", "selected"); }); $("input#op_impact").val(response[0].op_impact_description); $("input#zulu_date_time_out").val(response[0].zulu_date_time_out); $("input#zulu_date_time_in").val(response[0].zulu_date_time_in); $("input#outage_duration").val(response[0].outage_duration); $("select#request_source option").each(function(){ if($(this).val()==response[0].request_source_id) $(this).attr("selected", "selected"); }); $("input#zulu_monitor_status_start").val(response[0].zulu_monitor_status_start); $("input#zulu_monitor_status_stop").val(response[0].zulu_monitor_status_stop); $("input#zulu_date_time_etr").val(response[0].zulu_date_time_etr); $("select#validation_source option").each(function(){ if($(this).val()==response[0].validation_source_id) $(this).attr("selected", "selected"); }); $("select#element_type option").each(function(){ if($(this).val()==response[0].element_type_id) $(this).attr("selected", "selected"); }); $("input#element_id").val(response[0].element_id); $("input#validated").val(response[0].validated); $("input#hit_si").val(response[0].hit_si); $("select#domain_platform option").each(function(){ if($(this).val()==response[0].platform_domain_id) $(this).attr("selected", "selected"); }); }); } function populate_fault_tab() { } });<file_sep>/search.php <!doctype html> <?php require_once("template_engine.php"); ?> <html lang="en"> <head> <meta charset="utf-8"> <title>Global Trouble Management System</title> <script src="js/external/jquery/jquery.js"></script> <script src="js/jquery-ui.js"></script> <script src="js/flexgrid/js/flexigrid.js"></script> <script src="js/flexgrid/js/flexigrid.pack.js"></script> <script src="js/search.js"></script> <link rel="stylesheet" href="js/jquery-ui.css"> <link rel="stylesheet" href="js/flexgrid/css/flexigrid.css"> <link rel="stylesheet" href="css/styles.css"> </head> <body> <div id="main_container"> <div id="tickets_container" class="ui-widget-content"> <div id="tickets_header"> Matching Tm Action Request </div> <div id="tickets_grid_container"> <table class="flex1" style="display: none"></table> </div> </div> </div> </body> </html>
f7b1402c226bfb6171ce0d9174fdcfca203ca128
[ "JavaScript", "SQL", "PHP" ]
19
PHP
johndearman/gtms
806c4e6801bd771d53af17355b49103f765c5c37
4b47ad1c28acde271d8b5b25bef801591d3fb8b7
refs/heads/master
<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\RedmineApi; class TestController extends Controller { /** * Create a new authentication controller instance. */ public function __construct() { } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $path = public_path('products.json'); $old_data = \File::get($path); return view('test.create',compact('old_data')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * * @return \Illuminate\Http\Response */ public function store(Request $request) { $input = $request->input(); $path = public_path('products.json'); $old_data = \File::get($path); $data = json_decode($old_data); $input['date_time']=date('Y m d H:i:s',time()); $input['total_value']=($input['qty_in_stock']*$input['price_per_item']); $data[]=$input; \File::put($path,json_encode($data)); return \Response::json($input); } /** * Display the specified resource. * * @param int $id * * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * * @return \Illuminate\Http\Response */ public function destroy($id) { // } }
8d3602ad6395d628761df35657941ed554ca8a88
[ "PHP" ]
1
PHP
karanjilka/test
47fecdf135fd5d45db71d0c05475b052113ac58d
49cf1a00b1689ec53c647796ba4d6559662666cd
refs/heads/master
<repo_name>supercontainers/container-perf<file_sep>/packages/generate.sh #!/bin/bash -e # supply any text files to append to the build # one spec per line : ${ARGS:="$@"} for i in ${ARGS} do if [ -f ${i} ]; then while read line do EXTRA_SPEC="${EXTRA_SPEC}- ${line}$(echo '') " done < ${i} fi done TARG_DIR=${PWD} while read OS_SPEC do while read MPI_SPEC do APP_NAME=kokkos OS_NAME="$(echo ${OS_SPEC} | sed 's/:/ /g' | awk '{print $1}')" MPI_NAME="$(echo ${MPI_SPEC} | sed 's/[@+~.]/ /g' | awk '{print $1}')" echo "OS: ${OS_NAME}, MPI: ${MPI_NAME}" mkdir -p ${MPI_NAME} cp ./runtime-entrypoint.sh ./${MPI_NAME} pushd ./${MPI_NAME} rm -rf .spack-env rm -f spack.yaml rm -f Dockerfile.${OS_NAME} cat ${TARG_DIR}/spack.yaml.in | sed \ -e s,'@MPI_SPEC@',"${MPI_SPEC}",g \ -e s,'@MPI_NAME@',"${MPI_NAME}",g \ -e s,'@APP_NAME@',"${APP_NAME}",g \ -e s,'@OS_SPEC@',"${OS_SPEC}",g \ -e s,'@EXTRA_SPEC@',"${EXTRA_SPEC}",g \ > ./spack.yaml spack containerize | sed \ -e /'^ENTRYPOINT'/d \ -e s,'spack install','spack --env . install',g \ > Dockerfile.${OS_NAME} echo 'ENTRYPOINT [ "/runtime-entrypoint.sh" ]' >> Dockerfile.${OS_NAME} rm -rf .spack-env rm -f spack.yaml popd done < mpi.txt done < os.txt <file_sep>/build.sh #/bin/bash -e build() { docker-compose build --pull $@ } if [ -z "${1}" ]; then for i in ubuntu centos do for j in mpich openmpi mvapich do build ${i}-${j} done done else build $@ fi <file_sep>/packages/runtime-entrypoint.sh #!/bin/bash --rcfile /etc/profile -l # The purpose of this entrypoint is to embed some lightweight # performance monitoring in the application # if [ -z "${1}" ]; then exec /bin/bash -l fi # try to use timem if inside container : ${TIME:=$(which timem)} # if timem, not available, look for time : ${TIME:=$(which time)} # execute eval ${TIME} $@ <file_sep>/README.md # container-perf This repository builds several variants of MPI + Kokkos + CUDA for container performance benchmarking ## Overview This repository can be configured to build an array of containers for different operating systems and MPI variants. The MPI specifications are configured in `packages/mpi.txt` with one Spack spec per-line. The OS specifications are configured in `packages/os.txt` with one Spack spec per-line. CUDA, Kokkos, and a mini-app are always installed. Additionally Spack specs can be placed in files and passed to the `packages/generate.sh` script. A sample is placed in `packages/extra.txt`. ## Quick Start ```console cd packages ./generate.sh cd .. docker-compose build --pull ubuntu-mpich ``` ## Example ```console $ cd packages $ cat extra.txt timemory@develop +tools +cuda +cupti +gotcha +mpi +mpip_library +papi +gperftools cuda_arch=volta $ ./generate extra.txt OS: ubuntu, MPI: mpich OS: ubuntu, MPI: mvapich2 OS: ubuntu, MPI: openmpi OS: centos, MPI: mpich OS: centos, MPI: mvapich2 OS: centos, MPI: openmpi $ cat mpich/Dockerfile.ubuntu # Build stage with Spack pre-installed and ready to be used FROM spack/ubuntu-bionic:latest as builder # What we want to install and how we want to install it # is specified in a manifest file (spack.yaml) RUN mkdir /opt/spack-environment \ && (echo "spack:" \ && echo " specs:" \ && echo " - cuda" \ && echo " - kokkos build_type=Release +cuda cuda_arch=72 +cuda_lambda +cuda_uvm +hwloc +memkind +numactl +openmp +wrapper std=14" \ && echo " - mpich device=ch3 +hydra netmod=tcp ~pci pmi=pmi +romio ~slurm" \ && echo " - timemory@develop +tools +cuda +cupti +gotcha +mpi +mpip_library +papi +gperftools cuda_arch=volta" \ && echo " concretization: together" \ && echo " config:" \ && echo " install_tree: /opt/software" \ && echo " view: /opt/view") > /opt/spack-environment/spack.yaml # Install the software, remove unecessary deps RUN cd /opt/spack-environment && spack --env . install && spack gc -y # Modifications to the environment that are necessary to run RUN cd /opt/spack-environment && \ spack env activate --sh -d . >> /etc/profile.d/z10_spack_environment.sh SHELL ["/bin/bash", "--rcfile", "/etc/profile", "-l"] WORKDIR /tmp RUN git clone https://github.com/jrmadsen/kokkos-miniapps.git && \ cd kokkos-miniapps && \ git checkout submodules && \ mkdir -p build-container && \ cd build-container && \ cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_CXX_COMPILER=nvcc_wrapper -DUSE_MPI=ON .. && \ make install -j8 && \ cd /tmp && \ rm -rf /tmp/kokkos-miniapps # Bare OS image to run the installed executables FROM ubuntu:18.04 COPY --from=builder /opt/spack-environment /opt/spack-environment COPY --from=builder /opt/software /opt/software COPY --from=builder /opt/view /opt/view COPY --from=builder /etc/profile.d/z10_spack_environment.sh /etc/profile.d/z10_spack_environment.sh ENV OMP_PROC_BIND spread ENV OMP_PLACES threads ENV CUDA_HOME "/opt/view" ENV NVIDIA_REQUIRE_CUDA "cuda>=10.2" ENV NVIDIA_VISIBLE_DEVICES "all" ENV NVIDIA_DRIVER_CAPABILITIES "compute,utility" COPY ./runtime-entrypoint.sh /runtime-entrypoint.sh RUN echo 'export PS1="\[$(tput bold)\]\[$(tput setaf 1)\][kokkos-mpich]\[$(tput setaf 2)\]\u\[$(tput sgr0)\]:\w $ \[$(tput sgr0)\]"' >> ~/.bashrc LABEL "app"="kokkos" LABEL "mpi"="mpich" ENTRYPOINT [ "/runtime-entrypoint.sh" ] ``` ## Benchmarking ```console $ docker run -it --rm supercontainers/container-perf:ubuntu-mpich /usr/bin/lulesh-optimized --help To run other sizes, use -s <integer>. To run a fixed number of iterations, use -i <integer>. To run a more or less balanced region set, use -b <integer>. To change the relative costs of regions, use -c <integer>. To print out progress, use -p To write an output file for VisIt, use -v See help (-h) for more options ``` ### Sample Output ```console Running problem size 30^3 per domain until completion Num processors: 8 Num threads: 4 Total number of elements: 216000 To run other sizes, use -s <integer>. To run a fixed number of iterations, use -i <integer>. To run a more or less balanced region set, use -b <integer>. To change the relative costs of regions, use -c <integer>. To print out progress, use -p To write an output file for VisIt, use -v See help (-h) for more options cycle = 1, time = 6.852019e-07, dt=6.852019e-07 cycle = 2, time = 1.507444e-06, dt=8.222423e-07 cycle = 3, time = 1.789278e-06, dt=2.818333e-07 cycle = 4, time = 2.024630e-06, dt=2.353527e-07 cycle = 5, time = 2.234438e-06, dt=2.098079e-07 cycle = 6, time = 2.429254e-06, dt=1.948161e-07 cycle = 7, time = 2.614474e-06, dt=1.852199e-07 cycle = 8, time = 2.793376e-06, dt=1.789023e-07 cycle = 9, time = 2.968181e-06, dt=1.748048e-07 cycle = 10, time = 3.140521e-06, dt=1.723397e-07 cycle = 11, time = 3.347329e-06, dt=2.068076e-07 cycle = 12, time = 3.580825e-06, dt=2.334965e-07 cycle = 13, time = 3.801554e-06, dt=2.207292e-07 cycle = 14, time = 4.009569e-06, dt=2.080144e-07 cycle = 15, time = 4.204856e-06, dt=1.952872e-07 cycle = 16, time = 4.391294e-06, dt=1.864386e-07 cycle = 17, time = 4.572177e-06, dt=1.808824e-07 cycle = 18, time = 4.750330e-06, dt=1.781535e-07 cycle = 19, time = 4.928456e-06, dt=1.781255e-07 cycle = 20, time = 5.106581e-06, dt=1.781255e-07 cycle = 21, time = 5.284707e-06, dt=1.781255e-07 cycle = 22, time = 5.462832e-06, dt=1.781255e-07 cycle = 23, time = 5.640958e-06, dt=1.781255e-07 cycle = 24, time = 5.838115e-06, dt=1.971575e-07 cycle = 25, time = 6.035273e-06, dt=1.971575e-07 cycle = 26, time = 6.232430e-06, dt=1.971575e-07 cycle = 27, time = 6.457155e-06, dt=2.247252e-07 cycle = 28, time = 6.681880e-06, dt=2.247252e-07 cycle = 29, time = 6.950244e-06, dt=2.683634e-07 cycle = 30, time = 7.254776e-06, dt=3.045323e-07 cycle = 31, time = 7.547127e-06, dt=2.923506e-07 cycle = 32, time = 7.829604e-06, dt=2.824770e-07 cycle = 33, time = 8.105297e-06, dt=2.756935e-07 cycle = 34, time = 8.376591e-06, dt=2.712932e-07 cycle = 35, time = 8.645899e-06, dt=2.693089e-07 cycle = 36, time = 8.915208e-06, dt=2.693089e-07 cycle = 37, time = 9.184517e-06, dt=2.693089e-07 cycle = 38, time = 9.453826e-06, dt=2.693089e-07 cycle = 39, time = 9.723135e-06, dt=2.693089e-07 cycle = 40, time = 1.002492e-05, dt=3.017811e-07 cycle = 41, time = 1.032670e-05, dt=3.017811e-07 cycle = 42, time = 1.062848e-05, dt=3.017811e-07 cycle = 43, time = 1.093026e-05, dt=3.017811e-07 cycle = 44, time = 1.123204e-05, dt=3.017811e-07 cycle = 45, time = 1.153141e-05, dt=2.993676e-07 cycle = 46, time = 1.182441e-05, dt=2.930026e-07 cycle = 47, time = 1.211197e-05, dt=2.875624e-07 cycle = 48, time = 1.239508e-05, dt=2.831021e-07 cycle = 49, time = 1.267466e-05, dt=2.795814e-07 cycle = 50, time = 1.295174e-05, dt=2.770851e-07 Run completed: Problem size = 30 MPI tasks = 8 Iteration count = 50 Final Origin Energy = 1.750636e+07 Testing Plane 0 of Energy Array on rank 0: MaxAbsDiff = 2.328306e-09 TotalAbsDiff = 5.189477e-09 MaxRelDiff = 1.496717e-11 Elapsed time = 13.32 (s) Grind time (us/z/c) = 9.8646646 (per dom) ( 1.2330831 overall) FOM = 810.97537 (z/s) ```
3dcc6612d07ddb8707d866f0b941aa94e77d18fa
[ "Markdown", "Shell" ]
4
Shell
supercontainers/container-perf
40f5037f598472272840148f6161114376ef6adb
f6c94865d55d985ec5507f151031b8545ff8a628
refs/heads/master
<repo_name>shotaro0726/portfolio<file_sep>/portfolio/portfolioapp/admin.py from django.contrib import admin from .models import Profile, Idea_list, Opinion admin.site.register(Profile) admin.site.register(Idea_list) admin.site.register(Opinion) <file_sep>/portfolio/portfolioapp/urls.py from django.urls import path from .views import signupfunc, Home, Ideas_list, opinion, main_list, goodfunc, branchfunc, detailfunc, myfunc, Edit, Idea_edit, Delete app_name = 'portfolioapp' urlpatterns = [ path('', Home.as_view(), name='home'), path('signup/', signupfunc, name='signup'), path('ideas_list/', Ideas_list.as_view(), name='ideas_list'), path('opinion/<int:pk>', opinion, name='opinion'), path('main_list/<int:pk>', main_list, name='main_list'), path('good/<int:pk>', goodfunc, name='good'), path('branch/<int:pk>', branchfunc, name='branch'), path('detail/<int:pk>', detailfunc, name='detail'), path('my_page/', myfunc, name='my_page'), path('edit/<int:pk>', Edit.as_view(), name='edit'), path('idea_edit/<int:pk>', Idea_edit.as_view(), name='idea_edit'), path('delete/<int:pk>', Delete.as_view(), name='delte'), ] <file_sep>/venv_portfolio/bin/django-admin.py #!/Users/macuser/portfolio/venv_portfolio/bin/python from django.core import management if __name__ == "__main__": management.execute_from_command_line()
456fcb02e24c31cd28c825e6dfe645dbebe695bd
[ "Python" ]
3
Python
shotaro0726/portfolio
bc1d83818885d2b57845964fa4e2f11e82f99917
f83bf38269c17d10e59f2431b06ad8af90dae044
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class TriggerCameraView : MonoBehaviour { public CameraStyle Type; public CameraOrbit CameraScript; // Use this for initialization void Start () { CameraScript = FindObjectOfType<CameraOrbit>(); } void OnTriggerEnter(Collider obj) { if (obj.name == "Player") { string cameraSettings = "Walking"; switch (Type) { case CameraStyle.walking: cameraSettings = "Walking"; break; case CameraStyle.platform: cameraSettings = "Platform"; break; case CameraStyle.fighting: cameraSettings = "Fighting"; break; } CameraScript.ChangeCameraView(cameraSettings); } } } public enum CameraStyle { walking, platform, fighting }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Collectible : MonoBehaviour { public CollectibleType Type; public int Value; public float DistanceToTarget = 4; public float Speed = 2; [Header("Resources colors")] public Color LifeColor; public Color ExperienceColor; private GameObject _player; private bool _hasTarget = false; // Use this for initialization void Start () { _player = FindObjectOfType<PlayerResources>().gameObject; if (Type == CollectibleType.Life) { GetComponent<Light>().color = LifeColor; GetComponent<SpriteRenderer>().color = LifeColor; } else if (Type == CollectibleType.Experience) { GetComponent<Light>().color = ExperienceColor; GetComponent<SpriteRenderer>().color = ExperienceColor; } } // Update is called once per frame void Update () { // Si le collectible se situe à moins de DistanceToTarget, on switch le booleen hasTarget if (Vector3.Distance(transform.position, _player.transform.position) <= DistanceToTarget) _hasTarget = true; // Si il a trouvé sa cible if (_hasTarget) { // On désactive le comportement sine GetComponent<Sine>().Enabled = false; // On lui donne la direction de la cible à atteindre var direction = (_player.transform.position - transform.position).normalized; // On bouge sa position (le deltaTime est la valeur de temps qui s'est écoulé en deux appel de Update, c'est une valeur très faible et cela // permet de rendre la translation plus "smooth" transform.position += direction * Time.deltaTime * Speed; } } void OnTriggerEnter(Collider obj) { PlayerResources player; if (player = obj.GetComponent<PlayerResources>()) { if (Type == CollectibleType.Life) { player.AddLife(Value); } else if (Type == CollectibleType.Experience) { player.AddExperience(Value); } player.DisplayStats(); Destroy(gameObject); } } } public enum CollectibleType { Life, Experience }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "CameraSetting", menuName = "Hidden", order = 1)] public class CameraSetting : ScriptableObject { public List<CameraData> Data; public const int AIMING = 0; public const int WALKING = 1; public const int PLATFORM = 1; public const int FIGHTING = 1; } [System.Serializable] public struct CameraData { public string Name; public float Distance; public float HorizontalOffset; public float VerticalOffset; public float VerticalMinConstraint; public float VerticalMaxConstraint; }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovements : MonoBehaviour { public float WalkSpeed = 10.0f; public float Gravity = 9.0f; public float JumpStrength = 100f; public int MaxJumpCount = 2; private int _jumpCount = 0; public PlayerState State = PlayerState.walking; public Door door; private Transform _camera; private Vector3 _camForward; private Vector3 _move; private bool _jump; private CharacterController _controller; private float _verticalSpeed = 0.0f; void Start() { if (Camera.main != null) _camera = Camera.main.transform; else Debug.LogWarning("Pas de camera trouvée"); _controller = GetComponent<CharacterController>(); } void FixedUpdate() { if (GameController.Instance.State != GameState.running) return; if (Input.GetButton("jump") && _verticalSpeed < 0.1f) _verticalSpeed -= Gravity * Time.deltaTime; else _verticalSpeed -= Gravity; } void Update() { if (GameController.Instance.State != GameState.running) return; float horizontal = Input.GetAxis("horizontal"); float vertical = Input.GetAxis("vertical"); // Si le joueur touche le sol, on remet sa vitesse verticale à zéro if (_controller.isGrounded) { _verticalSpeed = 0; _jumpCount = 0; } if (State == PlayerState.walking) if (Input.GetButtonDown("jump")) Jump(); // On calcul l'angle de la caméra par rapport à la position du joueur afin d'adapter ses déplacement if (_camera != null) { _camForward = Vector3.Scale(_camera.forward, new Vector3(1, 0, 1)).normalized; _move = vertical * _camForward + horizontal * _camera.right; } else { _move = vertical * Vector3.forward + horizontal * Vector3.right; } if (State != PlayerState.climbing) transform.LookAt(_move + transform.position); // On applique le movement vertical _move.y = _verticalSpeed * Time.deltaTime; _controller.Move(_move * Time.deltaTime * WalkSpeed ); } public void Jump(float strengthMultiplier = 1.0f) { if (_jumpCount < MaxJumpCount) { _verticalSpeed = JumpStrength * strengthMultiplier; _jumpCount++; } } void OnControllerColliderHit(ControllerColliderHit hit) { if (hit.gameObject.name == "Wall") { var newRotation = Quaternion.LookRotation(-hit.normal); transform.rotation = newRotation; } } } public enum PlayerState { walking, climbing, crouching, flying, aiming }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Sine : MonoBehaviour { public SineType Type; public float Magnitude; public float Speed; public bool Enabled = true; float _sineValue; Vector3 _startPosition; Vector3 _startScale; // Use this for initialization void Start () { _startPosition = transform.position; _startScale = transform.localScale; } // Update is called once per frame void Update () { if (!Enabled) return; _sineValue = Mathf.Sin(Time.timeSinceLevelLoad * Speed) * Magnitude; if (Type == SineType.LeftToRight) { transform.position = _startPosition + transform.forward * _sineValue; } else if (Type == SineType.ForwardBackward) { transform.position = _startPosition + transform.right * _sineValue; } else if (Type == SineType.Vertical) { transform.position = _startPosition + transform.up * _sineValue; } else if (Type == SineType.Size) { transform.localScale = _startScale * (_sineValue + 0.2f); } } } public enum SineType { LeftToRight, ForwardBackward, Vertical, Size }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using SwissArmyKnife; public class GameController : Singleton<GameController> { public GameState State = GameState.running; } public enum GameState { running, keyboard, paused }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Switch : MonoBehaviour{ private bool _isOn = false; public TriggerableObject Target; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void Toggle() { if (_isOn) TurnOff(); else TurnOn(); } void TurnOn() { if (!_isOn) { _isOn = true; GetComponent<Animator>().SetTrigger("On"); Target.Activate(); } } void TurnOff() { if (_isOn) { _isOn = false; GetComponent<Animator>().SetTrigger("Off"); Target.Activate(); } } void OnTriggerStay(Collider col) { var obj = col.gameObject; if (obj.name == "Player") { UIManager.Instance.HintScript.Show("Appyuez sur $ pour ouvrir la porte", Hint.X_BUTTON); if (Input.GetButtonDown("interact")) Toggle(); } } void OnTriggerExit(Collider col) { if (col.name == "Player") { UIManager.Instance.HintScript.Hide(); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System; #if UNITY_EDITOR using UnityEditor; [CustomEditor(typeof(MovingFloor))] public class MovingFloorEditor : Editor { Vector3 NewCoordinates; int index; public override void OnInspectorGUI() { DrawDefaultInspector(); MovingFloor myScript = (MovingFloor)target; EditorGUILayout.LabelField("Modification des points", EditorStyles.boldLabel); EditorGUILayout.BeginVertical(); EditorGUILayout.BeginVertical("box"); GUILayout.Label("Ajouter"); NewCoordinates = EditorGUILayout.Vector3Field("Number of new objects", NewCoordinates); if (GUILayout.Button("Add point")) myScript.AddDestinationPoint(NewCoordinates); EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical("box"); GUILayout.Label("Supprimer"); index = EditorGUILayout.IntField("Index", index); index = Mathf.Clamp(index, 0, myScript.PointCount); if (GUILayout.Button("Destroy at index")) myScript.DestroyPoint(index); if (GUILayout.Button("Destroy last point")) myScript.DestroyLastPoint(); if (GUILayout.Button("Destroy all")) myScript.DestroyAll(); EditorGUILayout.EndVertical(); if (GUILayout.Button("Refresh list")) myScript.ReloadPointToList(); EditorGUILayout.EndVertical(); } } #endif public class MovingFloor : TriggerableObject { /// <summary> /// GameObject contenant les points de destinations /// </summary> public Transform Container; /// <summary> /// Plateforme ou objet à déplacer /// </summary> public Transform Platform; public float Speed = 10; /// <summary> /// Liste des points de destination /// </summary> public List<GameObject> DestinationPoints; public int PointCount { get { return DestinationPoints.Count; } } public bool StopBetweenTwoPoints = false; public float TimeToWait = 2; private float _waitingTime = 0; int _pointToReach = 1; #region Triggers void OnTriggerEnter(Collider col) { if (col.gameObject.name == "Player") col.gameObject.transform.SetParent(transform); } void OnTriggerExit(Collider col) { if (col.gameObject.name == "Player") col.gameObject.transform.SetParent(null); } #endregion #region Management public void AddDestinationPoint(Vector3 newCoord) { var go = new GameObject("Destination" + PointCount); go.transform.SetParent(Container); go.transform.position = newCoord; DestinationPoints.Add(go); } public void DestroyPoint(int index) { if (PointCount < 1) return; var pointToDestroy = DestinationPoints[index]; if (pointToDestroy != null) { DestroyImmediate(pointToDestroy); DestinationPoints.Remove(pointToDestroy); } } public void DestroyLastPoint() { if (PointCount > 0) { var pointToDestroy = DestinationPoints[PointCount - 1]; DestroyImmediate(pointToDestroy); DestinationPoints.Remove(pointToDestroy); } } public void DestroyAll() { for (int i = 0; i < PointCount; i++) { var pointToDestroy = DestinationPoints[i]; if (pointToDestroy != null) { DestroyImmediate(pointToDestroy); } } DestinationPoints.Clear(); } public void ReloadPointToList() { DestinationPoints.Clear(); int pointCount = Container.childCount; for (int i = 0; i < pointCount; i++) DestinationPoints.Add(Container.GetChild(i).gameObject); } #endregion public override void Activate() { IsActive = true; } void Start() { ReloadPointToList(); if (DestinationPoints.Count < 2) { Debug.LogError("Le script moving floor doit avoir au moins deux points de destination"); return; } Platform.position = DestinationPoints[0].transform.position; } void Update() { if (DestinationPoints.Count < 2) return; if (!IsActive) { return; } var step = Time.deltaTime * Speed; var pos = Platform.position; var pointToReach = DestinationPoints[_pointToReach].transform.position; Platform.position = Vector3.MoveTowards(pos, pointToReach, step); if (pos == pointToReach) { if (StopBetweenTwoPoints) { _waitingTime += Time.deltaTime; if (_waitingTime >= TimeToWait) { _waitingTime = 0; GoToNextPoint(); } } else { GoToNextPoint(); } } } void GoToNextPoint() { var next = _pointToReach + 1; if (next > PointCount - 1) { next = 0; } _pointToReach = next; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class BillboardEffect : MonoBehaviour { Camera _camera; // Use this for initialization void Start () { _camera = Camera.main; if (_camera == null) Debug.LogError("Aucune camera"); } // Update is called once per frame void Update () { if (_camera == null) return; var cameraPosition = _camera.gameObject.transform.position; transform.LookAt(cameraPosition); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using SwissArmyKnife; public class UIManager : Singleton<UIManager> { public Keyboard KeyboardScript; public GaugesManager GaugesManagerScript; public Hint HintScript; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using SwissArmyKnife; #if UNITY_EDITOR using UnityEditor; [CustomEditor(typeof(CameraOrbit))] public class CameraOrbitEditor : Editor { public override void OnInspectorGUI() { base.OnInspectorGUI(); CameraOrbit myScript = (CameraOrbit)target; if (GUILayout.Button("Aiming view")) { myScript.ChangeCameraView("Aiming"); } if (GUILayout.Button("Walking view")) { myScript.ChangeCameraView("Walking"); } if (GUILayout.Button("Platform view")) { myScript.ChangeCameraView("Platform"); } if (GUILayout.Button("Fighting view")) { myScript.ChangeCameraView("Fighting"); } } } #endif public class CameraOrbit : MonoBehaviour { public Transform Target; public Transform CameraTransform; public CameraSetting CameraSettings; [Header("Camera speed")] public float VerticalSpeed = 2; public float HorizontalSpeed = 3; [Header("Recentering parameters")] public float TimeBeforeRecenter = 3.0f; public float RecenterSpeedX = 3.0f; public float RecenterSpeedY = 5.0f; public bool recenter { get { return _recenter; } set { _recenter = value; } } public float distance { set { _distance = value; } get { return _distance; } } private float _time = 0; private bool _recenter = false; private float _minimumY = 0.0f; private float _maximumY = 50.0f; private float _distance = 10.0f; // Distance actuelle private float _newDistance = 10.0f; // Distance à atteindre private float _currentX = 0.0f; private float _currentY = 20.0f; // Use this for initialization void Start () { if (Target == null) Debug.LogError("A target must be link to this script"); CameraTransform = transform; if (CameraSettings != null) { var data = GetData("Walking"); SetCameraParameters(data); } else { Debug.LogWarning("Camera settings has not been found"); return; } } void FixedUpdate() { if (GameController.Instance.State != GameState.running) return; if (Input.GetButtonDown("recenterCamera")) RecenterCamera(); if (Input.GetAxis("aim") > 0) ChangeCameraView("Aiming"); else ChangeCameraView("Walking"); } // Update is called once per frame void Update () { if (GameController.Instance.State != GameState.running) return; float cameraX = Input.GetAxis("cameraX"); float cameraY = Input.GetAxis("cameraY"); // On récupère le composant CharacterController du player var controller = Target.GetComponentInParent<CharacterController>(); if (_newDistance != _distance) _distance = Mathf.Lerp(_distance, _newDistance, Time.deltaTime * 10); // Si ni la caméra bouge ni le joueur on incrémente le timer if (cameraX == 0 && cameraY == 0 && controller.velocity == Vector3.zero) { _time += Time.deltaTime; } else { _time = 0; _recenter = false; } // Si le temps qui s'est écoulé est supérieur ou égale à TimeBeforRecenter on recentre la caméra if (_time >= TimeBeforeRecenter) _recenter = true; if (_recenter) { _currentX = Mathf.LerpAngle(_currentX, Target.rotation.eulerAngles.y, Time.deltaTime * RecenterSpeedX); _currentY = Mathf.LerpAngle(_currentY, 20, Time.deltaTime * RecenterSpeedY); } _currentX += cameraX * HorizontalSpeed; _currentY += cameraY * VerticalSpeed; _currentY = Mathf.Clamp(_currentY, _minimumY, _maximumY); } void LateUpdate() { if (GameController.Instance.State != GameState.running) return; Vector3 direction = new Vector3(0, 0, -_distance); Quaternion rotation = Quaternion.Euler(_currentY, _currentX, 0); CameraTransform.position = Target.position + rotation * direction; CameraTransform.LookAt(Target.position); } public void RecenterCamera() { _recenter = true; } protected CameraData GetData(string settingName) { var datas = CameraSettings.Data; foreach (var setting in datas) if (setting.Name == settingName) return setting; return datas[CameraSetting.WALKING]; } void SetCameraParameters(CameraData data) { _newDistance = data.Distance; _minimumY = data.VerticalMinConstraint; _maximumY = data.VerticalMaxConstraint; } public void ChangeCameraView(string settingName) { var data = GetData(settingName); SetCameraParameters(data); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class Keyboard : MonoBehaviour { private string _alphabetReference = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "; private int _wordlength; private int _wordindex = 0; public GameObject Key; public Text UserAnswer; public Transform KeyHolder; public delegate void OnResolve(); public OnResolve Callback; public void InitializeKeybord() { var eventSystem = FindObjectOfType<EventSystem>(); for (int i = 0; i < _alphabetReference.Length; i++) { var key = CreateKey("Key " + _alphabetReference[i], _alphabetReference[i].ToString()); if (i == 0) eventSystem.firstSelectedGameObject = key; } var validateKey = CreateKey("Key validate", "-", Callback); //validateKey.GetComponent<Text>().font = Resources.Load<Font>("Arial"); var returnKey = CreateKey("Key return", ":", RemoveLetter); //returnKey.GetComponent<Text>().font = Resources.Load<Font>("Arial"); } GameObject CreateKey(string goName, string value) { var key = Instantiate(Key) as GameObject; key.name = goName; key.transform.SetParent(KeyHolder); var buttonText = key.GetComponentInChildren<Text>(); buttonText.text = value; key.GetComponent<Button>().onClick.AddListener(() => AddLetter(value[0])); return key; } GameObject CreateKey(string goName, string value, OnResolve callbackFunction) { var key = Instantiate(Key) as GameObject; key.name = goName; key.transform.SetParent(KeyHolder); var buttonText = key.GetComponentInChildren<Text>(); buttonText.text = value; key.GetComponent<Button>().onClick.AddListener(() => callbackFunction()); return key; } public void AddLetter(char letter) { var newtext = UserAnswer.text.ToCharArray(); newtext[_wordindex] = letter; _wordindex++; _wordindex = Mathf.Clamp(_wordindex, 0, _wordlength-1); // évite le if, met des limites : l'utilisateur ne pourra pas dépasser le nombre de lettres maximum Debug.Log(newtext.ToString()); UserAnswer.text = new string(newtext); Debug.Log("index " + _wordindex); } public void RemoveLetter() { var newtext = UserAnswer.text.ToCharArray(); if ((_wordindex == _wordlength-1) && (newtext[_wordindex] != '.')) { newtext[_wordindex] = '.'; } else { _wordindex--; _wordindex = Mathf.Clamp(_wordindex, 0, _wordlength - 1); newtext[_wordindex] = '.'; } UserAnswer.text = new string(newtext); Debug.Log("index " + _wordindex); } public void Call(int wordlength, OnResolve callbackFonction) { Callback = callbackFonction; InitializeKeybord(); _wordlength = wordlength; Open(); } void Open() { UserAnswer.text = ""; _wordindex = 0; GameController.Instance.State = GameState.keyboard; UserAnswer.gameObject.SetActive(true); KeyHolder.gameObject.SetActive(true); for (int i = 0; i<_wordlength; i++) { UserAnswer.text += "."; } } public void Close() { GameController.Instance.State = GameState.running; UserAnswer.gameObject.SetActive(false); KeyHolder.gameObject.SetActive(false); for (int i = 0; i < KeyHolder.childCount; i++) { Destroy(KeyHolder.GetChild(i).gameObject); } } void Update() { if (Input.GetButtonDown("cancel")) { Close(); } } } <file_sep> using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerResources: MonoBehaviour { public const int MAX_LIFE = 100; public const int MAX_EXP = 100; int _life = 50; int _exp = 0; int _level = 0; public int life { get { return _life; } } public int experience { get { return _exp; } } public int level { get { return _level; } } void Start() { UIManager.Instance.GaugesManagerScript.InitializeGauges(MAX_LIFE, life, MAX_EXP, experience, level); } public void AddLife(int value = 1) { var newValue = _life + value; _life = (newValue > MAX_LIFE) ? MAX_LIFE : newValue; UIManager.Instance.GaugesManagerScript.CalibrateLife(life); } public void SubstractLife(int value = 1) { var newValue = _life - value; _life = (newValue < 0) ? 0 : newValue; UIManager.Instance.GaugesManagerScript.CalibrateLife(life); } public void AddExperience(int value = 1) { var newValue = _exp + value; if (newValue <= MAX_EXP) { _exp = newValue; } else { AddLevel(); var valueToAdd = value - (MAX_EXP - _exp); _exp = valueToAdd; } UIManager.Instance.GaugesManagerScript.CalibrateExperience(experience); } public void AddLevel(int value = 1) { _level += value; UIManager.Instance.GaugesManagerScript.CalibrateLevel(level); } public void DisplayStats() { Debug.Log("Player stats :"); Debug.Log("Life = " + life); Debug.Log("-------------------"); Debug.Log("Experience = " + experience); Debug.Log("-------------------"); Debug.Log("Level = " + level); Debug.Log("-------------------"); } } <file_sep>using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine; using UnityEngine.UI; public class Hint : MonoBehaviour { public static int A_BUTTON = 0; public static int B_BUTTON = 1; public static int X_BUTTON = 2; public static int Y_BUTTON = 3; public static int START_BUTTON = 4; public static int MENU_BUTTON = 5; public List<Sprite> Icons; public GameObject goText; public GameObject goImage; private bool _isShowing = false; // Use this for initialization void Start() { } // Update is called once per frame void Update() { } /// <summary> /// Affiche un indice en jeu en bas de l'écran. Entrer le caractère $ pour indiquer la position d'une icône. /// </summary> /// <param name="hintString">La chaine de caractère à afficher</param> /// <param name="iconsIndexes">Index des icônes dans leur ordre d'apparition</param> public void Show(string hintString, params int[] iconsIndexes) { if (_isShowing) return; _isShowing = true; // On commence par vérifier si le nombre de $ dans la chaine correspond au nombre de paramètre iconsIndexes int iconsNumber = 0; for (int i = 0; i < hintString.Length; i++) if (hintString[i] == '$') iconsNumber++; // Si c'est pas le cas on renvoi une erreur if (iconsNumber != iconsIndexes.Length) return; string[] strings = hintString.Split('$'); string res = ""; for (int i = 0; i < strings.Length; i++) { CreateTextObject(strings[i]); if (i < strings.Length - 1) CreateImageObject(iconsIndexes[i]); } } public void Hide() { _isShowing = false; for (int i = 0; i < transform.childCount; i++) Destroy(transform.GetChild(i).gameObject); } void CreateTextObject(string text) { var goTxt = Instantiate(goText, transform) as GameObject; goTxt.GetComponent<Text>().text = text; } void CreateImageObject(int spriteIndex) { var goImg = Instantiate(goImage, transform) as GameObject; goImg.GetComponent<Image>().sprite = Icons[spriteIndex]; } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class GaugesManager : MonoBehaviour { public Image Life; public Image Experience; public Text Level; private float _maximumLife; private float _currentLife; private float _percentageLife; private float _maximumExperience; private float _currentExperience; private float _percentageExperience; // Update is called once per frame void Update () { Experience.fillAmount = Mathf.Lerp(Experience.fillAmount, _percentageExperience, Time.deltaTime * 5); Life.fillAmount = Mathf.Lerp(Life.fillAmount, _percentageLife, Time.deltaTime * 5); } public void InitializeGauges(float maxLife, float currentLife, float maxXP, float currentXP, int level) { _maximumLife = maxLife; _maximumExperience = maxXP; _currentLife = currentLife; _currentExperience = currentXP; CalibrateLife(_currentLife); CalibrateExperience(_currentExperience); CalibrateLevel(level); } public void CalibrateExperience(float newValue) { _currentExperience = newValue; _percentageExperience = newValue / _maximumExperience; } public void CalibrateLife(float newValue) { _currentLife = newValue; _percentageLife = newValue / _maximumLife; } public void CalibrateLevel(int newValue) { Level.text = "Level : " + newValue; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; abstract public class TriggerableObject : MonoBehaviour { public bool IsActive = false; abstract public void Activate(); } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Door : TriggerableObject { private bool _isOpen; private Animator _controller; public bool AutomaticallyClose = false; public bool IsOpen { get { return _isOpen; } } // Use this for initialization void Start () { IsActive = false; _controller = GetComponentInChildren<Animator>(); } // Update is called once per frame void Update () { } override public void Activate() { Toggle(); } public void Open() { if (!IsOpen) { _controller.SetTrigger("Open"); _isOpen = true; } } public void Close() { if (IsOpen) { _controller.SetTrigger("Close"); _isOpen = false; } } public void Toggle() { if (IsOpen) Close(); else Open(); } void OnTriggerStay(Collider col) { var obj = col.gameObject; if (obj.name == "Player") { RaycastHit hit; var pos = obj.transform.position; var forward = obj.transform.forward; Debug.DrawRay(pos, forward, Color.green); if (Physics.Raycast(pos, forward, out hit, 2)) { if (hit.collider.tag == "Door") { if (!IsOpen) UIManager.Instance.HintScript.Show("$", Hint.X_BUTTON); if (Input.GetButtonDown("interact")) Open(); } else UIManager.Instance.HintScript.Hide(); } } } void OnTriggerExit(Collider col) { if (col.name == "Player") { UIManager.Instance.HintScript.Hide(); if (AutomaticallyClose) Close(); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// Ce composent va permettre à la caméra de savoir si un obstacle se situe entre le joueur et elle-même. /// Si c'est le cas, la camera va se rapprocher du joueur. /// </summary> public class CameraRail : MonoBehaviour { // Position de la camera principale private Transform _camera; // Position du joueur private Transform _player; // Use this for initialization void Start () { _camera = Camera.main.transform; _player = FindObjectOfType<PlayerMovements>().gameObject.transform; } // Update is called once per frame void Update () { var position = transform.position; var playerPosition = _player.position; // On calcule la distance de l'objet de reference de la camera par rapport au joueur. // Cela servira pour déterminer la longueur du Raycast float distanceFromPlayer = Vector3.Distance(playerPosition, position); // On envoi un rayon du joueur vers la camera. La variable hits stockera tout les points de collision rencontrés par ce rayon. var hits = Physics.RaycastAll(playerPosition, position - playerPosition, distanceFromPlayer); // Si il y a au moins une collision if (hits.Length > 0) { // On récupère le point le plus proche du joueur grâce à la FoundTheNearestPoint. Vector3 nearestPoint = FindTheNearestPoint(hits, _player.position); // On lerp la position de la camera vers ce nouveau point _camera.position = nearestPoint; } else { // Sinon on lerp la position de la camera vers le point de référence de la camera _camera.position = Vector3.Lerp(_camera.position, transform.position, Time.deltaTime * 5); } } Vector3 FindTheNearestPoint(RaycastHit[] hits, Vector3 position) { Vector3 nearestPoint = hits[0].point ; foreach (var hit in hits) { var distanceFromPlayer = Vector3.Distance(hit.point, position); if (distanceFromPlayer < Vector3.Distance(nearestPoint, position)) nearestPoint = hit.point; } return nearestPoint; } Vector3 FindTheNearestPoint(Vector3[] points, Vector3 position) { Vector3 nearestPoint = points[0]; foreach (var point in points) { var distanceFromPlayer = Vector3.Distance(point, position); if (distanceFromPlayer < Vector3.Distance(nearestPoint, position)) nearestPoint = point; } return nearestPoint; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class CineCamera : MonoBehaviour { public GameObject _camera; public GameObject target; public bool IsActive = false; private bool _go; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (_go && IsActive) { _camera.GetComponent<CameraOrbit>().enabled = false; _camera.transform.position = Vector3.Lerp(_camera.transform.position, target.transform.position, Time.deltaTime * 5); _camera.transform.rotation = Quaternion.Lerp(_camera.transform.rotation, target.transform.rotation, Time.deltaTime * 5); } } void OnTriggerEnter(Collider col) { if (col.name == "Player") { _go = true; } } void OnTriggerExit(Collider col) { if (col.name == "Player") { _go = false; _camera.GetComponent<CameraOrbit>().enabled = true; _camera.GetComponent<CameraOrbit>().distance = Vector3.Distance(FindObjectOfType<PlayerResources>().transform.position, _camera.transform.position); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class TextualRiddle : MonoBehaviour { //Variables (publique commence par majuscule, privée commence par underscore) public string Answer; public Text UserAnswer; public bool OnTrigger = false; public TriggerableObject MV; public bool Resolved = false; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if ((OnTrigger) && (Input.GetButtonDown("interact")) && !Resolved) { GetComponent<CineCamera>().IsActive = true; UIManager.Instance.KeyboardScript.Call(Answer.Length, OnResolve); } } public void OnResolve() { Debug.Log(UserAnswer.text); if (UserAnswer.text == Answer) { Resolved = true; UIManager.Instance.KeyboardScript.Close(); GetComponent<CineCamera>().IsActive = false; MV.Activate(); UIManager.Instance.HintScript.Hide(); } } public void ShowText() { Debug.LogError("Bitule Shnaek"); UIManager.Instance.KeyboardScript.Close(); } void OnTriggerEnter(Collider col) { if (Resolved) //Si c'est résolu, quitte la fonction return; if (col.gameObject.name == "Player") { Debug.Log("Appuyez sur X"); OnTrigger = true; UIManager.Instance.HintScript.Show("Appuyez sur $ pour activer l'énigme", Hint.X_BUTTON); } } void OnTriggerExit(Collider col) { if (Resolved) //Si c'est résolu, quitte la fonction return; if (col.gameObject.name == "Player") { UIManager.Instance.HintScript.Hide(); OnTrigger = false; } } }
caabb581030be5fd09969ff86fb750e5fe2f022a
[ "C#" ]
20
C#
AnthonyFerry/hidden
11e6dba44a03fe24a02a3db79c937a0fda8f5fcc
7e5ee90e0b6a7d27d14f25b003965823c72612c4
refs/heads/main
<repo_name>TaylorSeguraVindas/ProyectoPOO<file_sep>/Proyecto/src/segura/taylor/dao/GeneroDAO.java package segura.taylor.dao; import segura.taylor.bl.entidades.Genero; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; /** * La clase DAO se encarga de realizar la conexión, lectura y escritura en la base de datos * @author <NAME> * @version 1.0 */ public class GeneroDAO { private ArrayList<Genero> generos = new ArrayList<>(); private Connection connection; /** * Método constructor * @param connection instancia de la clase Connection que define la conexión con la DB */ public GeneroDAO(Connection connection) { this.connection = connection; } /** * Este método se usa para escribir los datos de un nuevo genero en la base de datos * @param nuevoGenero instancia de la clase Genero que se desea guardar * @return true si el registro es exitoso, false si ocurre algún error */ public boolean save(Genero nuevoGenero) { try { Statement query = connection.createStatement(); String insert = "INSERT INTO generos (nombre, descripcion) VALUES "; insert += "('" + nuevoGenero.getNombre() + "','"; insert += nuevoGenero.getDescripcion() + "')"; query.execute(insert); return true; } catch (Exception e) { e.printStackTrace(); } return false; } /** * Este método se usa para sobreescribir los datos de un genero en la base de datos * @param generoActualizado instancia de la clase Genero con los cambios aplicados que se desean guardar * @return true si la escritura es exitosa, false si ocurre algún error * @throws Exception si no se puede conectar con la DB */ public boolean update(Genero generoActualizado) throws Exception { try { Statement query = connection.createStatement(); String update = "UPDATE generos "; update += "SET nombre = '" + generoActualizado.getNombre() + "',"; update += "descripcion = '" + generoActualizado.getDescripcion() + "'"; update += " WHERE idGenero = " + generoActualizado.getId(); query.execute(update); return true; } catch (Exception e){ e.printStackTrace(); } return false; } /** * Este método se usa para eliminar un genero de la base de datos * @param idGenero int que define el id del genero que se desea eliminar * @return true si la eliminación es exitosa, false si ocurre algún error * @throws Exception si no se puede conectar con la DB */ public boolean delete(int idGenero) throws Exception { try { Statement query = connection.createStatement(); String insert = "DELETE FROM generos WHERE idGenero = " + idGenero; query.execute(insert); return true; } catch (Exception e) { e.printStackTrace(); } return false; } /** * Este método se usa para obtener una lista con todos los generos guardados en la base de datos * @return una lista con todos los generos guardados * @throws SQLException si no se puede conectar con la DB */ public List<Genero> findAll() throws SQLException { Statement query = connection.createStatement(); ResultSet result = query.executeQuery("SELECT * FROM generos"); ArrayList<Genero> listaGeneros = new ArrayList<>(); while (result.next()) { Genero generoLeido = new Genero(); generoLeido.setId(result.getInt("idGenero")); generoLeido.setNombre(result.getString("nombre")); generoLeido.setDescripcion(result.getString("descripcion")); listaGeneros.add(generoLeido); } return Collections.unmodifiableList(listaGeneros); } /** * Este método se usa para buscar un genero usando como filtro su id * @param id int que define el id del genero que se desea encontrar * @return un objeto de tipo Optional que contiene una instancia de Genero si se encuentra una coincidencia * @throws SQLException si no se puede conectar con la DB * @see Optional * @see Genero */ public Optional<Genero> findByID(int id) throws SQLException { Statement query = connection.createStatement(); ResultSet result = query.executeQuery(("SELECT * FROM generos WHERE idGenero = " + id)); while (result.next()) { Genero generoLeido = new Genero(); generoLeido.setId(result.getInt("idGenero")); generoLeido.setNombre(result.getString("nombre")); generoLeido.setDescripcion(result.getString("descripcion")); return Optional.of(generoLeido); } return Optional.empty(); } /** * Este método se usa para buscar un genero usando como filtro su id * @param nombre String que define el nombre del genero que se desea encontrar * @return un objeto de tipo Optional que contiene una instancia de Genero si se encuentra una coincidencia * @throws SQLException si no se puede conectar con la DB * @see Optional * @see Genero */ public Optional<Genero> findByNombre(String nombre) throws SQLException { Statement query = connection.createStatement(); ResultSet result = query.executeQuery(("SELECT * FROM generos WHERE nombre = '" + nombre + "'")); while (result.next()) { Genero generoLeido = new Genero(); generoLeido.setId(result.getInt("idGenero")); generoLeido.setNombre(result.getString("nombre")); generoLeido.setDescripcion(result.getString("descripcion")); return Optional.of(generoLeido); } return Optional.empty(); } } <file_sep>/Proyecto/src/segura/taylor/bl/entidades/Biblioteca.java package segura.taylor.bl.entidades; import segura.taylor.bl.enums.TipoRepositorioCanciones; import java.time.LocalDate; import java.util.ArrayList; import java.util.Objects; import java.util.Optional; public class Biblioteca extends RepositorioCanciones { //Variables ArrayList<ListaReproduccion> listasDeReproduccion; //Propiedades public ArrayList<ListaReproduccion> getListasDeReproduccion() { return listasDeReproduccion; } public void setListasDeReproduccion(ArrayList<ListaReproduccion> listasDeReproduccion) { this.listasDeReproduccion = listasDeReproduccion; } //Contructores /** * Método constructor por defecto */ public Biblioteca() { this.tipoRepo = TipoRepositorioCanciones.BIBLIOTECA; this.listasDeReproduccion = new ArrayList<>(); } /** * Método constructor * @param nombre String que define el nombre * @param fechaCreacion LocalDate que define la fecha de creacion * @param canciones ArrayList que define las canciones que pertenecen a esta biblioteca * @param listasDeReproduccion ArrayList que define las listas de reproduccion que pertenecen a esta biblioteca */ public Biblioteca(String nombre, LocalDate fechaCreacion, ArrayList<Cancion> canciones, ArrayList<ListaReproduccion> listasDeReproduccion) { super(nombre, fechaCreacion, canciones); this.tipoRepo = TipoRepositorioCanciones.BIBLIOTECA; this.listasDeReproduccion = listasDeReproduccion; } //Metodos @Override public String toString() { return "Biblioteca{" + "id='" + id + '\'' + ", nombre='" + nombre + '\'' + ", fechaCreacion='" + fechaCreacion + '\'' + ", canciones=" + canciones + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; Biblioteca that = (Biblioteca) o; return Objects.equals(listasDeReproduccion, that.listasDeReproduccion); } @Override public int hashCode() { return Objects.hash(super.hashCode(), listasDeReproduccion); } /** * Método usado para agregar una lista de reproduccion a esta biblioteca * @param nuevaLista instancia de la clase ListaReproduccion que se desea agregar * @return true si la agregacion es exitosa, false si la lista ya ha sido agregada * @see ListaReproduccion */ public boolean agregarListaReproduccion(ListaReproduccion nuevaLista) { return listasDeReproduccion.add(nuevaLista); } /** * Método usado para remover una lista de reproduccion de esta biblioteca * @param pIdLista int que define el id de la lista de reproduccion que se desea remover * @return true si la eliminacion es exitosa, false si la lista no existe */ public boolean removerListaReproduccion(int pIdLista) { Optional<ListaReproduccion> listaEncontrada = buscarListaReproduccion(pIdLista); if(listaEncontrada.isPresent()) { return listasDeReproduccion.remove(listaEncontrada.get()); } return false; } /** * Método usado para buscar una lista de reproduccion en esta biblioteca * @param pIdLista int que define el id de la lista que se desea encontrar * @return objeto de tipo Optional que contiene una instancia de ListaReproduccion si se encuentra una coincidencia */ public Optional<ListaReproduccion> buscarListaReproduccion(int pIdLista) { for (ListaReproduccion lista : listasDeReproduccion) { if(pIdLista == lista.getId()) { return Optional.of(lista); } } return Optional.empty(); } } <file_sep>/Proyecto/src/segura/taylor/dao/ArtistaDAO.java package segura.taylor.dao; import segura.taylor.bl.entidades.Artista; import java.sql.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; /** * La clase DAO se encarga de realizar la conexión, lectura y escritura en la base de datos * @author <NAME> * @version 1.0 */ public class ArtistaDAO { private ArrayList<Artista> artistas = new ArrayList<>(); private Connection connection; private PaisDAO paisDAO; private GeneroDAO generoDAO; private ArtistasAlbumDAO artistasAlbumDAO; /** * Método constructor * @param connection instancia de la clase Connection que define la conexión con la DB */ public ArtistaDAO(Connection connection) { this.connection = connection; this.paisDAO = new PaisDAO(connection); this.generoDAO = new GeneroDAO(connection); this.artistasAlbumDAO = new ArtistasAlbumDAO(connection); } /** * Este método se usa para escribir los datos de un nuevo artista en la base de datos * @param nuevoArtista instancia de la clase artista que se desea guardar * @return true si el registro es exitoso, false si ocurre algún error * @throws Exception si no se puede conectar con la DB */ public boolean save(Artista nuevoArtista) throws Exception { try { Statement query = connection.createStatement(); String insert = "INSERT INTO artistas (nombre, apellidos, nombreArtistico, fechaNacimiento, fechaDefuncion, descripcion, idPais, idGenero) VALUES "; insert += "('" + nuevoArtista.getNombre() + "','"; insert += nuevoArtista.getApellidos() + "','"; insert += nuevoArtista.getNombreArtistico() + "','"; insert += Date.valueOf(nuevoArtista.getFechaNacimiento()) + "',"; insert += (nuevoArtista.getFechaDefuncion() != null) ? "'" + Date.valueOf(nuevoArtista.getFechaDefuncion()) + "','" : null + ",'"; insert += nuevoArtista.getDescripcion() + "',"; insert += nuevoArtista.getPaisNacimiento().getId() + ","; insert += nuevoArtista.getGenero().getId() + ")"; System.out.println("Ejecuto query: " + insert); query.execute(insert); return true; } catch (Exception e){ e.printStackTrace(); } return false; } /** * Este método se usa para sobreescribir los datos de un artista en la base de datos * @param artistaActualizado instancia de la clase artista con los cambios aplicados que se desean guardar * @return true si la escritura es exitosa, false si ocurre algún error * @throws Exception si no se puede conectar con la DB */ public boolean update(Artista artistaActualizado) throws Exception { try { Statement query = connection.createStatement(); String update = "UPDATE artistas "; update += "SET nombre = '" + artistaActualizado.getNombre() + "',"; update += "apellidos = '" + artistaActualizado.getApellidos() + "',"; update += "nombreArtistico = '" + artistaActualizado.getNombreArtistico() + "',"; update += "fechaDefuncion = " + ((artistaActualizado.getFechaDefuncion() != null) ? "'" + Date.valueOf(artistaActualizado.getFechaDefuncion()) + "'," : null + ","); update += "descripcion = '" + artistaActualizado.getDescripcion() + "'"; update += " WHERE idArtista = " + artistaActualizado.getId(); System.out.println("Ejecuto query: " + update); query.execute(update); return true; } catch (Exception e){ e.printStackTrace(); } return false; } /** * Este método se usa para eliminar un artista de la base de datos * @param idArtista int que define el id del artista que se desea eliminar * @return true si la eliminación es exitosa, false si ocurre algún error * @throws Exception si no se puede conectar con la DB */ public boolean delete(int idArtista) throws Exception { try { Statement query = connection.createStatement(); String delete = "DELETE FROM artistas WHERE idArtista = " + idArtista; query.execute(delete); return true; } catch (Exception e){ e.printStackTrace(); } return false; } /** * Este método se usa para obtener una lista con todos los artistas guardados en la base de datos * @return una lista con todos los artistas guardados * @throws SQLException si no se puede conectar con la DB */ public List<Artista> findAll() throws SQLException { Statement query = connection.createStatement(); ResultSet result = query.executeQuery("SELECT * FROM artistas"); ArrayList<Artista> listaArtistas = new ArrayList<>(); while (result.next()) { Artista artistaLeido = new Artista(); artistaLeido.setId(result.getInt("idArtista")); artistaLeido.setNombre(result.getString("nombre")); artistaLeido.setApellidos(result.getString("apellidos")); artistaLeido.setNombreArtistico(result.getString("nombreArtistico")); artistaLeido.setFechaNacimiento(result.getDate("fechaNacimiento").toLocalDate()); //Nulleable Date fechaDefuncion = result.getDate("fechaDefuncion"); artistaLeido.setFechaDefuncion((fechaDefuncion != null) ? fechaDefuncion.toLocalDate() : null); artistaLeido.setDescripcion(result.getString("descripcion")); artistaLeido.setPaisNacimiento(paisDAO.findByID(result.getInt("idPais")).get()); artistaLeido.setGenero(generoDAO.findByID(result.getInt("idGenero")).get()); listaArtistas.add(artistaLeido); } return Collections.unmodifiableList(listaArtistas); } /** * Este método se usa para buscar un artista usando como filtro su id * @param id int que define el id del artista que se desea encontrar * @return un objeto de tipo Optional que contiene una instancia de Artista si se encuentra una coincidencia * @throws SQLException si no se puede conectar con la DB * @see Optional * @see Artista */ public Optional<Artista> findByID(int id) throws SQLException { Statement query = connection.createStatement(); ResultSet result = query.executeQuery("SELECT * FROM artistas where idArtista = " + id); while (result.next()) { Artista artistaLeido = new Artista(); artistaLeido.setId(result.getInt("idArtista")); artistaLeido.setNombre(result.getString("nombre")); artistaLeido.setApellidos(result.getString("apellidos")); artistaLeido.setNombreArtistico(result.getString("nombreArtistico")); artistaLeido.setFechaNacimiento(result.getDate("fechaNacimiento").toLocalDate()); //Nulleable Date fechaDefuncion = result.getDate("fechaDefuncion"); artistaLeido.setFechaDefuncion((fechaDefuncion != null) ? fechaDefuncion.toLocalDate() : null); artistaLeido.setDescripcion(result.getString("descripcion")); artistaLeido.setPaisNacimiento(paisDAO.findByID(result.getInt("idPais")).get()); artistaLeido.setGenero(generoDAO.findByID(result.getInt("idGenero")).get()); return Optional.of(artistaLeido); } return Optional.empty(); } /** * Este método se usa para buscar un artista usando como filtro su id * @param nombre String que define el nombre artistico del artista que se desea encontrar * @return un objeto de tipo Optional que contiene una instancia de Artista si se encuentra una coincidencia * @throws SQLException si no se puede conectar con la DB * @see Optional * @see Artista */ public Optional<Artista> findByNombre(String nombre) throws SQLException { Statement query = connection.createStatement(); ResultSet result = query.executeQuery("SELECT * FROM artistas where nombreArtistico = '" + nombre + "'"); while (result.next()) { Artista artistaLeido = new Artista(); artistaLeido.setId(result.getInt("idArtista")); artistaLeido.setNombre(result.getString("nombre")); artistaLeido.setApellidos(result.getString("apellidos")); artistaLeido.setNombreArtistico(result.getString("nombreArtistico")); artistaLeido.setFechaNacimiento(result.getDate("fechaNacimiento").toLocalDate()); //Nulleable Date fechaDefuncion = result.getDate("fechaDefuncion"); artistaLeido.setFechaDefuncion((fechaDefuncion != null) ? fechaDefuncion.toLocalDate() : null); artistaLeido.setDescripcion(result.getString("descripcion")); artistaLeido.setPaisNacimiento(paisDAO.findByID(result.getInt("idPais")).get()); artistaLeido.setGenero(generoDAO.findByID(result.getInt("idGenero")).get()); return Optional.of(artistaLeido); } return Optional.empty(); } public ArrayList<Artista> findArtistasAlbum(int idAlbum) throws SQLException { String idArtistas = artistasAlbumDAO.getIdArtistasAlbum(idAlbum); if(idArtistas == "") { //No hay artistas return new ArrayList<>(); } Statement query = connection.createStatement(); ResultSet result = query.executeQuery("SELECT * FROM artistas WHERE idArtista IN (" + idArtistas + ")"); ArrayList<Artista> listaArtistas = new ArrayList<>(); while (result.next()) { Artista artistaLeido = new Artista(); artistaLeido.setId(result.getInt("idArtista")); artistaLeido.setNombre(result.getString("nombre")); artistaLeido.setApellidos(result.getString("apellidos")); artistaLeido.setNombreArtistico(result.getString("nombreArtistico")); artistaLeido.setFechaNacimiento(result.getDate("fechaNacimiento").toLocalDate()); //Nulleable Date fechaDefuncion = result.getDate("fechaDefuncion"); artistaLeido.setFechaDefuncion((fechaDefuncion != null) ? fechaDefuncion.toLocalDate() : null); artistaLeido.setDescripcion(result.getString("descripcion")); artistaLeido.setPaisNacimiento(paisDAO.findByID(result.getInt("idPais")).get()); artistaLeido.setGenero(generoDAO.findByID(result.getInt("idGenero")).get()); listaArtistas.add(artistaLeido); } return listaArtistas; } } <file_sep>/Proyecto/src/segura/taylor/bl/entidades/Admin.java package segura.taylor.bl.entidades; import segura.taylor.bl.enums.TipoUsuario; import java.time.LocalDate; import java.util.Objects; public class Admin extends Usuario { //Variables private LocalDate fechaCreacion; //Propiedades public LocalDate getFechaCreacion() { return fechaCreacion; } public void setFechaCreacion(LocalDate fechaCreacion) { this.fechaCreacion = fechaCreacion; } //Constructores /** * Método constructor por defecto */ public Admin(){ this.tipoUsuario = TipoUsuario.ADMIN; } /** * Método constructor * @param correo String que define el correo * @param contrasenna String que define la contraseña * @param nombre String que define el nombre * @param apellidos String que define los apellidos * @param imagenPerfil String que define la ruta de la imagen de perfil * @param nombreUsuario String que define el nombre de usuario * @param fechaCreacion LocalDate que define la fecha de creacion */ public Admin(String correo, String contrasenna, String nombre, String apellidos, String imagenPerfil, String nombreUsuario, LocalDate fechaCreacion) { super(correo, contrasenna, nombre, apellidos, imagenPerfil, nombreUsuario); this.tipoUsuario = TipoUsuario.ADMIN; this.fechaCreacion = fechaCreacion; } //Metodos @Override public String toString() { return "Admin{" + "fechaCreacion='" + fechaCreacion + '\'' + ", id='" + id + '\'' + ", tipoUsuario=" + tipoUsuario + ", correo='" + correo + '\'' + ", contrasenna='" + contrasenna + '\'' + ", nombre='" + nombre + '\'' + ", apellidos='" + apellidos + '\'' + ", imagenPerfil='" + imagenPerfil + '\'' + ", nombreUsuario='" + nombreUsuario + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; Admin admin = (Admin) o; return Objects.equals(fechaCreacion, admin.fechaCreacion); } @Override public int hashCode() { return Objects.hash(super.hashCode(), fechaCreacion); } } <file_sep>/Proyecto/src/segura/taylor/bl/entidades/Album.java package segura.taylor.bl.entidades; import segura.taylor.bl.enums.TipoRepositorioCanciones; import segura.taylor.bl.interfaces.IComboBoxItem; import java.time.LocalDate; import java.util.ArrayList; import java.util.Objects; import java.util.Optional; public class Album extends RepositorioCanciones implements IComboBoxItem { //Variables private LocalDate fechaLanzamiento; private String imagen; private ArrayList<Artista> artistas; //Propiedades public LocalDate getFechaLanzamiento() { return fechaLanzamiento; } public void setFechaLanzamiento(LocalDate fechaLanzamiento) { this.fechaLanzamiento = fechaLanzamiento; } public String getImagen() { return imagen; } public void setImagen(String imagen) { this.imagen = imagen; } public ArrayList<Artista> getArtistas() { return artistas; } public void setArtistas(ArrayList<Artista> artistas) { this.artistas = artistas; } //Constructores /** * Método constructor por defecto */ public Album() { this.tipoRepo = TipoRepositorioCanciones.ALBUM; this.artistas = new ArrayList<>(); } /** * Método constructor * @param nombre String que define el nombre * @param fechaCreacion LocalDate que define la fecha de creacion * @param canciones Arraylist que define las canciones que pertenecen a este album * @param fechaLanzamiento LocalDate que define la fecha de lanzamiento * @param imagen String que define la ruta de la imagen * @param artistas ArrayList que define los artistas que pertenecen a este album */ public Album(String nombre, LocalDate fechaCreacion, ArrayList<Cancion> canciones, LocalDate fechaLanzamiento, String imagen, ArrayList<Artista> artistas) { super(nombre, fechaCreacion, canciones); this.tipoRepo = TipoRepositorioCanciones.ALBUM; this.fechaLanzamiento = fechaLanzamiento; this.imagen = imagen; this.artistas = artistas; } //Metodos @Override public String toString() { return "Album{" + "id='" + id + '\'' + ", nombre='" + nombre + '\'' + ", fechaCreacion='" + fechaCreacion + '\'' + ", fechaLanzamiento='" + fechaLanzamiento + '\'' + ", imagen='" + imagen + '\'' + ", canciones=" + canciones + ", artistas=" + artistas + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; Album album = (Album) o; return Objects.equals(fechaLanzamiento, album.fechaLanzamiento) && Objects.equals(imagen, album.imagen) && Objects.equals(artistas, album.artistas); } @Override public int hashCode() { return Objects.hash(super.hashCode(), fechaLanzamiento, imagen, artistas); } /** * Método usado para agregar un artista a este album * @param artista instancia de la clase Artista que será almacenado * @return true si la agregación es exitosa, false si el artista ya ha sido agregado * @see Artista */ public boolean agregarArtista(Artista artista){ if(!tieneArtista(artista)){ artistas.add(artista); return true; } return false; } /** * Método usado para remover un artista de este album * @param artista instancia de la clase Artista que se desea remover * @return true si la eliminación es exitosa, false si el artista no existe * @see Artista */ public boolean removerArtista(Artista artista){ if(tieneArtista(artista)){ artistas.remove(artista); return true; } return false; } /** * Método para verificar si un artista está siendo almacenado en este album * @param artista instancia de la clase Artista de la que se desea verificar su existencia * @return true si existe, false si no */ public boolean tieneArtista(Artista artista){ for (Artista objArtista: artistas) { if(objArtista.equals(artista)){ return true; } } return false; } /** * Método usado para buscar un artista en los almacenados usando como filtro su id * @param idArtista int que define el id del artista que se desea encontrar * @return objeto de tipo Optional que contiene una instancia de Artista si se encuentra una coincidencia * @see Optional * @see Artista */ public Optional<Artista> buscarArtista(int idArtista){ for (Artista objArtista: artistas) { if(objArtista.getId() == idArtista){ return Optional.of(objArtista); } } return Optional.empty(); } @Override public String toComboBoxItem() { return id + "-" + nombre; } } <file_sep>/Proyecto/src/segura/taylor/bl/enums/TipoListaReproduccion.java package segura.taylor.bl.enums; public enum TipoListaReproduccion { PARA_USUARIO, PARA_TIENDA } <file_sep>/Proyecto/src/segura/taylor/bl/entidades/Genero.java package segura.taylor.bl.entidades; import segura.taylor.bl.interfaces.IComboBoxItem; import java.util.Objects; public class Genero implements IComboBoxItem { //Variables public static int idGeneros = 0; private int id; private String nombre; private String descripcion; //Propiedades public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } //Constructores /** * Método constructor por defecto */ public Genero(){} /** * Método constructor * @param nombre String que define el nombre * @param descripcion String que define la descripcion */ public Genero(String nombre, String descripcion) { this.id = 0; this.nombre = nombre; this.descripcion = descripcion; } //Metodos @Override public String toString() { return "Genero{" + "id='" + id + '\'' + ", nombre='" + nombre + '\'' + ", descripcion='" + descripcion + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Genero genero = (Genero) o; return Objects.equals(id, genero.id) && Objects.equals(nombre, genero.nombre) && Objects.equals(descripcion, genero.descripcion); } @Override public int hashCode() { return Objects.hash(id, nombre, descripcion); } @Override public String toComboBoxItem() { return id + "-" + nombre; } } <file_sep>/Proyecto/javaDoc/index-files/index-11.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="es"> <head> <!-- Generated by javadoc (1.8.0_181) on Sun Dec 20 18:03:50 CST 2020 --> <title>M-Index</title> <meta name="date" content="2020-12-20"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> <script type="text/javascript" src="../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="M-Index"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-10.html">Prev Letter</a></li> <li><a href="index-12.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-files/index-11.html" target="_top">Frames</a></li> <li><a href="index-11.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="contentContainer"><a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">L</a>&nbsp;<a href="index-11.html">M</a>&nbsp;<a href="index-12.html">N</a>&nbsp;<a href="index-13.html">O</a>&nbsp;<a href="index-14.html">P</a>&nbsp;<a href="index-15.html">R</a>&nbsp;<a href="index-16.html">S</a>&nbsp;<a href="index-17.html">T</a>&nbsp;<a href="index-18.html">U</a>&nbsp;<a href="index-19.html">V</a>&nbsp;<a href="index-20.html">Y</a>&nbsp;<a name="I:M"> <!-- --> </a> <h2 class="title">M</h2> <dl> <dt><a href="../segura/taylor/Main.html" title="class in segura.taylor"><span class="typeNameLink">Main</span></a> - Class in <a href="../segura/taylor/package-summary.html">segura.taylor</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/Main.html#Main--">Main()</a></span> - Constructor for class segura.taylor.<a href="../segura/taylor/Main.html" title="class in segura.taylor">Main</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/Main.html#main-java.lang.String:A-">main(String[])</a></span> - Static method in class segura.taylor.<a href="../segura/taylor/Main.html" title="class in segura.taylor">Main</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/ControladorGeneral.html#menuIniciarSesion--">menuIniciarSesion()</a></span> - Method in class segura.taylor.controlador.<a href="../segura/taylor/controlador/ControladorGeneral.html" title="class in segura.taylor.controlador">ControladorGeneral</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/ControladorGeneral.html#menuPrincipal-boolean-">menuPrincipal(boolean)</a></span> - Method in class segura.taylor.controlador.<a href="../segura/taylor/controlador/ControladorGeneral.html" title="class in segura.taylor.controlador">ControladorGeneral</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/ControladorGeneral.html#menuRegistroCliente--">menuRegistroCliente()</a></span> - Method in class segura.taylor.controlador.<a href="../segura/taylor/controlador/ControladorGeneral.html" title="class in segura.taylor.controlador">ControladorGeneral</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/album/ControladorRegistroAlbum.html#modificando">modificando</a></span> - Static variable in class segura.taylor.controlador.interfaz.album.<a href="../segura/taylor/controlador/interfaz/album/ControladorRegistroAlbum.html" title="class in segura.taylor.controlador.interfaz.album">ControladorRegistroAlbum</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/artista/ControladorRegistroArtista.html#modificando">modificando</a></span> - Static variable in class segura.taylor.controlador.interfaz.artista.<a href="../segura/taylor/controlador/interfaz/artista/ControladorRegistroArtista.html" title="class in segura.taylor.controlador.interfaz.artista">ControladorRegistroArtista</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/cancion/ControladorRegistroCancion.html#modificando">modificando</a></span> - Static variable in class segura.taylor.controlador.interfaz.cancion.<a href="../segura/taylor/controlador/interfaz/cancion/ControladorRegistroCancion.html" title="class in segura.taylor.controlador.interfaz.cancion">ControladorRegistroCancion</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/compositor/ControladorRegistroCompositor.html#modificando">modificando</a></span> - Static variable in class segura.taylor.controlador.interfaz.compositor.<a href="../segura/taylor/controlador/interfaz/compositor/ControladorRegistroCompositor.html" title="class in segura.taylor.controlador.interfaz.compositor">ControladorRegistroCompositor</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/genero/ControladorRegistroGenero.html#modificando">modificando</a></span> - Static variable in class segura.taylor.controlador.interfaz.genero.<a href="../segura/taylor/controlador/interfaz/genero/ControladorRegistroGenero.html" title="class in segura.taylor.controlador.interfaz.genero">ControladorRegistroGenero</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/listaReproduccion/ControladorRegistroListaReproduccion.html#modificando">modificando</a></span> - Static variable in class segura.taylor.controlador.interfaz.listaReproduccion.<a href="../segura/taylor/controlador/interfaz/listaReproduccion/ControladorRegistroListaReproduccion.html" title="class in segura.taylor.controlador.interfaz.listaReproduccion">ControladorRegistroListaReproduccion</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/pais/ControladorRegistroPais.html#modificando">modificando</a></span> - Static variable in class segura.taylor.controlador.interfaz.pais.<a href="../segura/taylor/controlador/interfaz/pais/ControladorRegistroPais.html" title="class in segura.taylor.controlador.interfaz.pais">ControladorRegistroPais</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/usuarios/ControladorRegistroAdmin.html#modificando">modificando</a></span> - Static variable in class segura.taylor.controlador.interfaz.usuarios.<a href="../segura/taylor/controlador/interfaz/usuarios/ControladorRegistroAdmin.html" title="class in segura.taylor.controlador.interfaz.usuarios">ControladorRegistroAdmin</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/usuarios/ControladorRegistroCliente.html#modificando">modificando</a></span> - Static variable in class segura.taylor.controlador.interfaz.usuarios.<a href="../segura/taylor/controlador/interfaz/usuarios/ControladorRegistroCliente.html" title="class in segura.taylor.controlador.interfaz.usuarios">ControladorRegistroCliente</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/admin/ControladorVentanaPrincipalAdmin.html#modificarAdmin--">modificarAdmin()</a></span> - Method in class segura.taylor.controlador.interfaz.admin.<a href="../segura/taylor/controlador/interfaz/admin/ControladorVentanaPrincipalAdmin.html" title="class in segura.taylor.controlador.interfaz.admin">ControladorVentanaPrincipalAdmin</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/bl/gestor/Gestor.html#modificarAlbum-int-java.lang.String-java.lang.String-">modificarAlbum(int, String, String)</a></span> - Method in class segura.taylor.bl.gestor.<a href="../segura/taylor/bl/gestor/Gestor.html" title="class in segura.taylor.bl.gestor">Gestor</a></dt> <dd> <div class="block">Método usado para modificar un album</div> </dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/admin/ControladorAlbunesAdmin.html#modificarAlbum--">modificarAlbum()</a></span> - Method in class segura.taylor.controlador.interfaz.admin.<a href="../segura/taylor/controlador/interfaz/admin/ControladorAlbunesAdmin.html" title="class in segura.taylor.controlador.interfaz.admin">ControladorAlbunesAdmin</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/album/ControladorRegistroAlbum.html#modificarAlbum--">modificarAlbum()</a></span> - Method in class segura.taylor.controlador.interfaz.album.<a href="../segura/taylor/controlador/interfaz/album/ControladorRegistroAlbum.html" title="class in segura.taylor.controlador.interfaz.album">ControladorRegistroAlbum</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/bl/gestor/Gestor.html#modificarArtista-int-java.lang.String-java.lang.String-java.lang.String-java.time.LocalDate-java.lang.String-">modificarArtista(int, String, String, String, LocalDate, String)</a></span> - Method in class segura.taylor.bl.gestor.<a href="../segura/taylor/bl/gestor/Gestor.html" title="class in segura.taylor.bl.gestor">Gestor</a></dt> <dd> <div class="block">Método usado para modificar un artista</div> </dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/admin/ControladorArtistasAdmin.html#modificarArtista--">modificarArtista()</a></span> - Method in class segura.taylor.controlador.interfaz.admin.<a href="../segura/taylor/controlador/interfaz/admin/ControladorArtistasAdmin.html" title="class in segura.taylor.controlador.interfaz.admin">ControladorArtistasAdmin</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/artista/ControladorRegistroArtista.html#modificarArtista--">modificarArtista()</a></span> - Method in class segura.taylor.controlador.interfaz.artista.<a href="../segura/taylor/controlador/interfaz/artista/ControladorRegistroArtista.html" title="class in segura.taylor.controlador.interfaz.artista">ControladorRegistroArtista</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/bl/gestor/Gestor.html#modificarCalificacion-int-int-">modificarCalificacion(int, int)</a></span> - Method in class segura.taylor.bl.gestor.<a href="../segura/taylor/bl/gestor/Gestor.html" title="class in segura.taylor.bl.gestor">Gestor</a></dt> <dd> <div class="block">Método usado para modificar una calificacion</div> </dd> <dt><span class="memberNameLink"><a href="../segura/taylor/bl/gestor/Gestor.html#modificarCancion-int-java.lang.String-java.lang.String-double-int-int-int-java.time.LocalDate-double-">modificarCancion(int, String, String, double, int, int, int, LocalDate, double)</a></span> - Method in class segura.taylor.bl.gestor.<a href="../segura/taylor/bl/gestor/Gestor.html" title="class in segura.taylor.bl.gestor">Gestor</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/admin/ControladorCancionesAdmin.html#modificarCancion--">modificarCancion()</a></span> - Method in class segura.taylor.controlador.interfaz.admin.<a href="../segura/taylor/controlador/interfaz/admin/ControladorCancionesAdmin.html" title="class in segura.taylor.controlador.interfaz.admin">ControladorCancionesAdmin</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/cancion/ControladorRegistroCancion.html#modificarCancion--">modificarCancion()</a></span> - Method in class segura.taylor.controlador.interfaz.cancion.<a href="../segura/taylor/controlador/interfaz/cancion/ControladorRegistroCancion.html" title="class in segura.taylor.controlador.interfaz.cancion">ControladorRegistroCancion</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/cliente/ControladorBibliotecaCliente.html#modificarCancion--">modificarCancion()</a></span> - Method in class segura.taylor.controlador.interfaz.cliente.<a href="../segura/taylor/controlador/interfaz/cliente/ControladorBibliotecaCliente.html" title="class in segura.taylor.controlador.interfaz.cliente">ControladorBibliotecaCliente</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/bl/gestor/Gestor.html#modificarCompositor-int-java.lang.String-java.lang.String-">modificarCompositor(int, String, String)</a></span> - Method in class segura.taylor.bl.gestor.<a href="../segura/taylor/bl/gestor/Gestor.html" title="class in segura.taylor.bl.gestor">Gestor</a></dt> <dd> <div class="block">Método usado para modificar un compositor</div> </dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/admin/ControladorCompositoresAdmin.html#modificarCompositor--">modificarCompositor()</a></span> - Method in class segura.taylor.controlador.interfaz.admin.<a href="../segura/taylor/controlador/interfaz/admin/ControladorCompositoresAdmin.html" title="class in segura.taylor.controlador.interfaz.admin">ControladorCompositoresAdmin</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/compositor/ControladorRegistroCompositor.html#modificarCompositor--">modificarCompositor()</a></span> - Method in class segura.taylor.controlador.interfaz.compositor.<a href="../segura/taylor/controlador/interfaz/compositor/ControladorRegistroCompositor.html" title="class in segura.taylor.controlador.interfaz.compositor">ControladorRegistroCompositor</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/bl/gestor/Gestor.html#modificarContrasennaUsuario-int-java.lang.String-">modificarContrasennaUsuario(int, String)</a></span> - Method in class segura.taylor.bl.gestor.<a href="../segura/taylor/bl/gestor/Gestor.html" title="class in segura.taylor.bl.gestor">Gestor</a></dt> <dd> <div class="block">Método usado para modificar la contraseña de un usuario</div> </dd> <dt><span class="memberNameLink"><a href="../segura/taylor/bl/gestor/Gestor.html#modificarGenero-int-java.lang.String-java.lang.String-">modificarGenero(int, String, String)</a></span> - Method in class segura.taylor.bl.gestor.<a href="../segura/taylor/bl/gestor/Gestor.html" title="class in segura.taylor.bl.gestor">Gestor</a></dt> <dd> <div class="block">Método usaodo para modificar un genero</div> </dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/admin/ControladorGenerosAdmin.html#modificarGenero--">modificarGenero()</a></span> - Method in class segura.taylor.controlador.interfaz.admin.<a href="../segura/taylor/controlador/interfaz/admin/ControladorGenerosAdmin.html" title="class in segura.taylor.controlador.interfaz.admin">ControladorGenerosAdmin</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/genero/ControladorRegistroGenero.html#modificarGenero--">modificarGenero()</a></span> - Method in class segura.taylor.controlador.interfaz.genero.<a href="../segura/taylor/controlador/interfaz/genero/ControladorRegistroGenero.html" title="class in segura.taylor.controlador.interfaz.genero">ControladorRegistroGenero</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/bl/gestor/Gestor.html#modificarListaReproduccion-int-java.lang.String-java.lang.String-java.lang.String-">modificarListaReproduccion(int, String, String, String)</a></span> - Method in class segura.taylor.bl.gestor.<a href="../segura/taylor/bl/gestor/Gestor.html" title="class in segura.taylor.bl.gestor">Gestor</a></dt> <dd> <div class="block">Método usado para modificar una lista de reproduccion</div> </dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/admin/ControladorListasReproduccionAdmin.html#modificarListaReproduccion--">modificarListaReproduccion()</a></span> - Method in class segura.taylor.controlador.interfaz.admin.<a href="../segura/taylor/controlador/interfaz/admin/ControladorListasReproduccionAdmin.html" title="class in segura.taylor.controlador.interfaz.admin">ControladorListasReproduccionAdmin</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/cliente/ControladorVentanaPrincipalCliente.html#modificarListaReproduccion--">modificarListaReproduccion()</a></span> - Method in class segura.taylor.controlador.interfaz.cliente.<a href="../segura/taylor/controlador/interfaz/cliente/ControladorVentanaPrincipalCliente.html" title="class in segura.taylor.controlador.interfaz.cliente">ControladorVentanaPrincipalCliente</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/listaReproduccion/ControladorRegistroListaReproduccion.html#modificarListaReproduccion--">modificarListaReproduccion()</a></span> - Method in class segura.taylor.controlador.interfaz.listaReproduccion.<a href="../segura/taylor/controlador/interfaz/listaReproduccion/ControladorRegistroListaReproduccion.html" title="class in segura.taylor.controlador.interfaz.listaReproduccion">ControladorRegistroListaReproduccion</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/bl/gestor/Gestor.html#modificarPais-int-java.lang.String-java.lang.String-">modificarPais(int, String, String)</a></span> - Method in class segura.taylor.bl.gestor.<a href="../segura/taylor/bl/gestor/Gestor.html" title="class in segura.taylor.bl.gestor">Gestor</a></dt> <dd> <div class="block">Método usado para modificar un pais</div> </dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/admin/ControladorPaisesAdmin.html#modificarPais--">modificarPais()</a></span> - Method in class segura.taylor.controlador.interfaz.admin.<a href="../segura/taylor/controlador/interfaz/admin/ControladorPaisesAdmin.html" title="class in segura.taylor.controlador.interfaz.admin">ControladorPaisesAdmin</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/pais/ControladorRegistroPais.html#modificarPais--">modificarPais()</a></span> - Method in class segura.taylor.controlador.interfaz.pais.<a href="../segura/taylor/controlador/interfaz/pais/ControladorRegistroPais.html" title="class in segura.taylor.controlador.interfaz.pais">ControladorRegistroPais</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/bl/gestor/Gestor.html#modificarUsuario-int-java.lang.String-java.lang.String-java.lang.String-java.lang.String-java.lang.String-">modificarUsuario(int, String, String, String, String, String)</a></span> - Method in class segura.taylor.bl.gestor.<a href="../segura/taylor/bl/gestor/Gestor.html" title="class in segura.taylor.bl.gestor">Gestor</a></dt> <dd> <div class="block">Método usado para modificar un usuario</div> </dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/admin/ControladorUsuariosAdmin.html#modificarUsuario--">modificarUsuario()</a></span> - Method in class segura.taylor.controlador.interfaz.admin.<a href="../segura/taylor/controlador/interfaz/admin/ControladorUsuariosAdmin.html" title="class in segura.taylor.controlador.interfaz.admin">ControladorUsuariosAdmin</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/cliente/ControladorVentanaPrincipalCliente.html#modificarUsuario--">modificarUsuario()</a></span> - Method in class segura.taylor.controlador.interfaz.cliente.<a href="../segura/taylor/controlador/interfaz/cliente/ControladorVentanaPrincipalCliente.html" title="class in segura.taylor.controlador.interfaz.cliente">ControladorVentanaPrincipalCliente</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/usuarios/ControladorRegistroAdmin.html#modificarUsuario--">modificarUsuario()</a></span> - Method in class segura.taylor.controlador.interfaz.usuarios.<a href="../segura/taylor/controlador/interfaz/usuarios/ControladorRegistroAdmin.html" title="class in segura.taylor.controlador.interfaz.usuarios">ControladorRegistroAdmin</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/usuarios/ControladorLogin.html#mostrar--">mostrar()</a></span> - Method in class segura.taylor.controlador.interfaz.usuarios.<a href="../segura/taylor/controlador/interfaz/usuarios/ControladorLogin.html" title="class in segura.taylor.controlador.interfaz.usuarios">ControladorLogin</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/ui/dialogos/AlertDialog.html#mostrar-java.lang.String-java.lang.String-">mostrar(String, String)</a></span> - Method in class segura.taylor.ui.dialogos.<a href="../segura/taylor/ui/dialogos/AlertDialog.html" title="class in segura.taylor.ui.dialogos">AlertDialog</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/ui/dialogos/VentanaCambiarContrasenna.html#mostrar--">mostrar()</a></span> - Method in class segura.taylor.ui.dialogos.<a href="../segura/taylor/ui/dialogos/VentanaCambiarContrasenna.html" title="class in segura.taylor.ui.dialogos">VentanaCambiarContrasenna</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/ui/dialogos/VentanaContrasennaTemporal.html#mostrar--">mostrar()</a></span> - Method in class segura.taylor.ui.dialogos.<a href="../segura/taylor/ui/dialogos/VentanaContrasennaTemporal.html" title="class in segura.taylor.ui.dialogos">VentanaContrasennaTemporal</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/ui/dialogos/VentanaFiltroArtistasAdmin.html#mostrar--">mostrar()</a></span> - Method in class segura.taylor.ui.dialogos.<a href="../segura/taylor/ui/dialogos/VentanaFiltroArtistasAdmin.html" title="class in segura.taylor.ui.dialogos">VentanaFiltroArtistasAdmin</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/ui/dialogos/VentanaFiltroCancionesAdmin.html#mostrar--">mostrar()</a></span> - Method in class segura.taylor.ui.dialogos.<a href="../segura/taylor/ui/dialogos/VentanaFiltroCancionesAdmin.html" title="class in segura.taylor.ui.dialogos">VentanaFiltroCancionesAdmin</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/ui/dialogos/VentanaFiltroCancionesBiblioteca.html#mostrar--">mostrar()</a></span> - Method in class segura.taylor.ui.dialogos.<a href="../segura/taylor/ui/dialogos/VentanaFiltroCancionesBiblioteca.html" title="class in segura.taylor.ui.dialogos">VentanaFiltroCancionesBiblioteca</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/ui/dialogos/VentanaFiltrosCancionesTienda.html#mostrar--">mostrar()</a></span> - Method in class segura.taylor.ui.dialogos.<a href="../segura/taylor/ui/dialogos/VentanaFiltrosCancionesTienda.html" title="class in segura.taylor.ui.dialogos">VentanaFiltrosCancionesTienda</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/ui/dialogos/VentanaMetodoPago.html#mostrar--">mostrar()</a></span> - Method in class segura.taylor.ui.dialogos.<a href="../segura/taylor/ui/dialogos/VentanaMetodoPago.html" title="class in segura.taylor.ui.dialogos">VentanaMetodoPago</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/ui/dialogos/VentanaSeleccionarArtista.html#mostrar--">mostrar()</a></span> - Method in class segura.taylor.ui.dialogos.<a href="../segura/taylor/ui/dialogos/VentanaSeleccionarArtista.html" title="class in segura.taylor.ui.dialogos">VentanaSeleccionarArtista</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/ui/dialogos/VentanaSeleccionarCancion.html#mostrar--">mostrar()</a></span> - Method in class segura.taylor.ui.dialogos.<a href="../segura/taylor/ui/dialogos/VentanaSeleccionarCancion.html" title="class in segura.taylor.ui.dialogos">VentanaSeleccionarCancion</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/ui/dialogos/VentanaSeleccionarLista.html#mostrar--">mostrar()</a></span> - Method in class segura.taylor.ui.dialogos.<a href="../segura/taylor/ui/dialogos/VentanaSeleccionarLista.html" title="class in segura.taylor.ui.dialogos">VentanaSeleccionarLista</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/ui/dialogos/VentanaVerificarCorreo.html#mostrar--">mostrar()</a></span> - Method in class segura.taylor.ui.dialogos.<a href="../segura/taylor/ui/dialogos/VentanaVerificarCorreo.html" title="class in segura.taylor.ui.dialogos">VentanaVerificarCorreo</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/ui/dialogos/YesNoDialog.html#mostrar-java.lang.String-java.lang.String-">mostrar(String, String)</a></span> - Method in class segura.taylor.ui.dialogos.<a href="../segura/taylor/ui/dialogos/YesNoDialog.html" title="class in segura.taylor.ui.dialogos">YesNoDialog</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/tienda/ControladorTienda.html#mostrarAlbumes--">mostrarAlbumes()</a></span> - Method in class segura.taylor.controlador.interfaz.tienda.<a href="../segura/taylor/controlador/interfaz/tienda/ControladorTienda.html" title="class in segura.taylor.controlador.interfaz.tienda">ControladorTienda</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/admin/ControladorVentanaPrincipalAdmin.html#mostrarAlbunes--">mostrarAlbunes()</a></span> - Method in class segura.taylor.controlador.interfaz.admin.<a href="../segura/taylor/controlador/interfaz/admin/ControladorVentanaPrincipalAdmin.html" title="class in segura.taylor.controlador.interfaz.admin">ControladorVentanaPrincipalAdmin</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/admin/ControladorVentanaPrincipalAdmin.html#mostrarArtistas--">mostrarArtistas()</a></span> - Method in class segura.taylor.controlador.interfaz.admin.<a href="../segura/taylor/controlador/interfaz/admin/ControladorVentanaPrincipalAdmin.html" title="class in segura.taylor.controlador.interfaz.admin">ControladorVentanaPrincipalAdmin</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/cliente/ControladorVentanaPrincipalCliente.html#mostrarBiblioteca--">mostrarBiblioteca()</a></span> - Method in class segura.taylor.controlador.interfaz.cliente.<a href="../segura/taylor/controlador/interfaz/cliente/ControladorVentanaPrincipalCliente.html" title="class in segura.taylor.controlador.interfaz.cliente">ControladorVentanaPrincipalCliente</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/admin/ControladorVentanaPrincipalAdmin.html#mostrarCanciones--">mostrarCanciones()</a></span> - Method in class segura.taylor.controlador.interfaz.admin.<a href="../segura/taylor/controlador/interfaz/admin/ControladorVentanaPrincipalAdmin.html" title="class in segura.taylor.controlador.interfaz.admin">ControladorVentanaPrincipalAdmin</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/tienda/ControladorTienda.html#mostrarCanciones--">mostrarCanciones()</a></span> - Method in class segura.taylor.controlador.interfaz.tienda.<a href="../segura/taylor/controlador/interfaz/tienda/ControladorTienda.html" title="class in segura.taylor.controlador.interfaz.tienda">ControladorTienda</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/admin/ControladorVentanaPrincipalAdmin.html#mostrarCompositores--">mostrarCompositores()</a></span> - Method in class segura.taylor.controlador.interfaz.admin.<a href="../segura/taylor/controlador/interfaz/admin/ControladorVentanaPrincipalAdmin.html" title="class in segura.taylor.controlador.interfaz.admin">ControladorVentanaPrincipalAdmin</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/ui/dialogos/VentanaCambiarContrasenna.html#mostrarForzado-java.lang.String-">mostrarForzado(String)</a></span> - Method in class segura.taylor.ui.dialogos.<a href="../segura/taylor/ui/dialogos/VentanaCambiarContrasenna.html" title="class in segura.taylor.ui.dialogos">VentanaCambiarContrasenna</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/admin/ControladorVentanaPrincipalAdmin.html#mostrarGeneros--">mostrarGeneros()</a></span> - Method in class segura.taylor.controlador.interfaz.admin.<a href="../segura/taylor/controlador/interfaz/admin/ControladorVentanaPrincipalAdmin.html" title="class in segura.taylor.controlador.interfaz.admin">ControladorVentanaPrincipalAdmin</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/admin/ControladorVentanaPrincipalAdmin.html#mostrarInfoAlbum--">mostrarInfoAlbum()</a></span> - Method in class segura.taylor.controlador.interfaz.admin.<a href="../segura/taylor/controlador/interfaz/admin/ControladorVentanaPrincipalAdmin.html" title="class in segura.taylor.controlador.interfaz.admin">ControladorVentanaPrincipalAdmin</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/cliente/ControladorVentanaPrincipalCliente.html#mostrarInfoAlbum--">mostrarInfoAlbum()</a></span> - Method in class segura.taylor.controlador.interfaz.cliente.<a href="../segura/taylor/controlador/interfaz/cliente/ControladorVentanaPrincipalCliente.html" title="class in segura.taylor.controlador.interfaz.cliente">ControladorVentanaPrincipalCliente</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/admin/ControladorVentanaPrincipalAdmin.html#mostrarInfoCancion--">mostrarInfoCancion()</a></span> - Method in class segura.taylor.controlador.interfaz.admin.<a href="../segura/taylor/controlador/interfaz/admin/ControladorVentanaPrincipalAdmin.html" title="class in segura.taylor.controlador.interfaz.admin">ControladorVentanaPrincipalAdmin</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/cliente/ControladorVentanaPrincipalCliente.html#mostrarInfoCancion--">mostrarInfoCancion()</a></span> - Method in class segura.taylor.controlador.interfaz.cliente.<a href="../segura/taylor/controlador/interfaz/cliente/ControladorVentanaPrincipalCliente.html" title="class in segura.taylor.controlador.interfaz.cliente">ControladorVentanaPrincipalCliente</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/admin/ControladorVentanaPrincipalAdmin.html#mostrarInfoListaReproduccion--">mostrarInfoListaReproduccion()</a></span> - Method in class segura.taylor.controlador.interfaz.admin.<a href="../segura/taylor/controlador/interfaz/admin/ControladorVentanaPrincipalAdmin.html" title="class in segura.taylor.controlador.interfaz.admin">ControladorVentanaPrincipalAdmin</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/cliente/ControladorVentanaPrincipalCliente.html#mostrarInfoListaReproduccion--">mostrarInfoListaReproduccion()</a></span> - Method in class segura.taylor.controlador.interfaz.cliente.<a href="../segura/taylor/controlador/interfaz/cliente/ControladorVentanaPrincipalCliente.html" title="class in segura.taylor.controlador.interfaz.cliente">ControladorVentanaPrincipalCliente</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/admin/ControladorVentanaPrincipalAdmin.html#mostrarListasReproduccion--">mostrarListasReproduccion()</a></span> - Method in class segura.taylor.controlador.interfaz.admin.<a href="../segura/taylor/controlador/interfaz/admin/ControladorVentanaPrincipalAdmin.html" title="class in segura.taylor.controlador.interfaz.admin">ControladorVentanaPrincipalAdmin</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/tienda/ControladorTienda.html#mostrarListasReproduccion--">mostrarListasReproduccion()</a></span> - Method in class segura.taylor.controlador.interfaz.tienda.<a href="../segura/taylor/controlador/interfaz/tienda/ControladorTienda.html" title="class in segura.taylor.controlador.interfaz.tienda">ControladorTienda</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/admin/ControladorVentanaPrincipalAdmin.html#mostrarPaises--">mostrarPaises()</a></span> - Method in class segura.taylor.controlador.interfaz.admin.<a href="../segura/taylor/controlador/interfaz/admin/ControladorVentanaPrincipalAdmin.html" title="class in segura.taylor.controlador.interfaz.admin">ControladorVentanaPrincipalAdmin</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/admin/ControladorVentanaPrincipalAdmin.html#mostrarTienda--">mostrarTienda()</a></span> - Method in class segura.taylor.controlador.interfaz.admin.<a href="../segura/taylor/controlador/interfaz/admin/ControladorVentanaPrincipalAdmin.html" title="class in segura.taylor.controlador.interfaz.admin">ControladorVentanaPrincipalAdmin</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/cliente/ControladorVentanaPrincipalCliente.html#mostrarTienda--">mostrarTienda()</a></span> - Method in class segura.taylor.controlador.interfaz.cliente.<a href="../segura/taylor/controlador/interfaz/cliente/ControladorVentanaPrincipalCliente.html" title="class in segura.taylor.controlador.interfaz.cliente">ControladorVentanaPrincipalCliente</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../segura/taylor/controlador/interfaz/admin/ControladorVentanaPrincipalAdmin.html#mostrarUsuarios--">mostrarUsuarios()</a></span> - Method in class segura.taylor.controlador.interfaz.admin.<a href="../segura/taylor/controlador/interfaz/admin/ControladorVentanaPrincipalAdmin.html" title="class in segura.taylor.controlador.interfaz.admin">ControladorVentanaPrincipalAdmin</a></dt> <dd>&nbsp;</dd> </dl> <a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">L</a>&nbsp;<a href="index-11.html">M</a>&nbsp;<a href="index-12.html">N</a>&nbsp;<a href="index-13.html">O</a>&nbsp;<a href="index-14.html">P</a>&nbsp;<a href="index-15.html">R</a>&nbsp;<a href="index-16.html">S</a>&nbsp;<a href="index-17.html">T</a>&nbsp;<a href="index-18.html">U</a>&nbsp;<a href="index-19.html">V</a>&nbsp;<a href="index-20.html">Y</a>&nbsp;</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-10.html">Prev Letter</a></li> <li><a href="index-12.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-files/index-11.html" target="_top">Frames</a></li> <li><a href="index-11.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html> <file_sep>/Proyecto/src/segura/taylor/dao/ListasReproduccionBibliotecaDAO.java package segura.taylor.dao; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class ListasReproduccionBibliotecaDAO { private Connection connection; public ListasReproduccionBibliotecaDAO(Connection connection) { this.connection = connection; } public boolean save(int idBiblioteca, int idLista) { try { Statement query = connection.createStatement(); String insert = "INSERT INTO listas_biblioteca (idBiblioteca, idLista) VALUES "; insert += "(" + idBiblioteca + ","; insert += idLista + ")"; query.execute(insert); return true; } catch (Exception e){ e.printStackTrace(); } return false; } public boolean delete(int idBiblioteca, int idLista) { try { Statement query = connection.createStatement(); String insert = "DELETE FROM listas_biblioteca WHERE idBiblioteca = " + idBiblioteca + " and idLista = " + idLista; query.execute(insert); return true; } catch (Exception e){ e.printStackTrace(); } return false; } public String getIdListasReproduccionBiblioteca(int idBiblioteca) throws SQLException { Statement query = connection.createStatement(); ResultSet result = query.executeQuery("SELECT * FROM listas_biblioteca WHERE idBiblioteca = " + idBiblioteca); String listaCanciones = ""; while (result.next()) { listaCanciones += result.getString("idLista") + ","; } if(listaCanciones.length() > 0) { listaCanciones = listaCanciones.substring(0, listaCanciones.length()-1); //Quitar la última coma } return listaCanciones; } } <file_sep>/Proyecto/src/segura/taylor/bl/enums/TipoUsuario.java package segura.taylor.bl.enums; public enum TipoUsuario { CLIENTE, CREADOR, ADMIN } <file_sep>/Proyecto/src/segura/taylor/bl/enums/TipoRepositorioCanciones.java package segura.taylor.bl.enums; public enum TipoRepositorioCanciones { BIBLIOTECA, LISTA_REPRODUCCION, ALBUM } <file_sep>/Proyecto/src/segura/taylor/bl/entidades/Compositor.java package segura.taylor.bl.entidades; import segura.taylor.bl.interfaces.IComboBoxItem; import java.time.LocalDate; import java.util.Objects; public class Compositor implements IComboBoxItem { //Variables public static int idCompositores = 0; private int id; private String nombre; private String apellidos; private Pais paisNacimiento; private Genero genero; private LocalDate fechaNacimiento; private int edad; //Propiedades public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getApellidos() { return apellidos; } public void setApellidos(String apellidos) { this.apellidos = apellidos; } public Pais getPaisNacimiento() { return paisNacimiento; } public void setPaisNacimiento(Pais paisNacimiento) { this.paisNacimiento = paisNacimiento; } public Genero getGenero() { return genero; } public void setGenero(Genero genero) { this.genero = genero; } public LocalDate getFechaNacimiento() { return fechaNacimiento; } public void setFechaNacimiento(LocalDate fechaNacimiento) { this.fechaNacimiento = fechaNacimiento; } public int getEdad() { return edad; } public void setEdad(int edad) { this.edad = edad; } //Tablas public String getNombrePais() { return paisNacimiento.getNombre(); } public String getNombreGenero() { return genero.getNombre(); } //Constructores /** * Método constructor por defecto */ public Compositor(){} /** * Método constuctor * @param nombre String que define el nombre * @param apellidos String que define los apellidos * @param paisNacimiento instancia de la clase Pais que define el pais de nacimiento * @param genero instancia de la clase Genero que define el genero * @param fechaNacimiento LocalDate que define la fecha de nacimiento * @param edad int que define la edad * @see Pais * @see Genero */ public Compositor(String nombre, String apellidos, Pais paisNacimiento, Genero genero, LocalDate fechaNacimiento, int edad) { this.id = 0; this.nombre = nombre; this.apellidos = apellidos; this.paisNacimiento = paisNacimiento; this.genero = genero; this.fechaNacimiento = fechaNacimiento; this.edad = edad; } //Metodos @Override public String toString() { return "Compositor{" + "id='" + id + '\'' + ", nombre='" + nombre + '\'' + ", apellidos='" + apellidos + '\'' + ", paisNacimiento='" + paisNacimiento + '\'' + ", genero='" + genero + '\'' + ", fechaNacimiento='" + fechaNacimiento + '\'' + ", edad=" + edad + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Compositor that = (Compositor) o; return id == that.id && edad == that.edad && Objects.equals(nombre, that.nombre) && Objects.equals(apellidos, that.apellidos) && Objects.equals(paisNacimiento, that.paisNacimiento) && Objects.equals(genero, that.genero) && Objects.equals(fechaNacimiento, that.fechaNacimiento); } @Override public int hashCode() { return Objects.hash(id, nombre, apellidos, paisNacimiento, genero, fechaNacimiento, edad); } @Override public String toComboBoxItem() { return id + "-" + nombre; } } <file_sep>/Proyecto/src/segura/taylor/dao/RepositorioCancionesDAO.java package segura.taylor.dao; import segura.taylor.bl.entidades.*; import segura.taylor.bl.enums.TipoListaReproduccion; import segura.taylor.bl.enums.TipoRepositorioCanciones; import java.sql.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; /** * La clase DAO se encarga de realizar la conexión, lectura y escritura en la base de datos * @author <NAME> * @version 1.0 */ public class RepositorioCancionesDAO { private ArrayList<RepositorioCanciones> repoCanciones = new ArrayList<>(); private Connection connection; private CancionDAO cancionDAO; private ArtistaDAO artistaDAO; private ListasReproduccionBibliotecaDAO listasBibliotecaDAO; /** * Método constructor * @param connection instancia de la clase Connection que define la conexión con la DB */ public RepositorioCancionesDAO(Connection connection) { this.connection = connection; this.cancionDAO = new CancionDAO(connection); this.artistaDAO = new ArtistaDAO(connection); this.listasBibliotecaDAO = new ListasReproduccionBibliotecaDAO(connection); } /** * Este método se usa para escribir los datos de un nuevo repositorio de canciones en la base de datos * @param nuevoRepositorioCanciones instancia de la clase RepositorioCanciones que se desea guardar * @return el id del repositorio guardado, -1 si ocurre algún error */ public int save(RepositorioCanciones nuevoRepositorioCanciones) { String insert = ""; if(nuevoRepositorioCanciones.getTipoRepo().equals(TipoRepositorioCanciones.BIBLIOTECA)) { Biblioteca nuevaBiblioteca = (Biblioteca) nuevoRepositorioCanciones; insert = "INSERT INTO bibliotecas (nombre, fechaCreacion) VALUES "; insert += "('" + nuevaBiblioteca.getNombre() + "','"; insert += Date.valueOf(nuevaBiblioteca.getFechaCreacion()) + "')"; } else if (nuevoRepositorioCanciones.getTipoRepo().equals(TipoRepositorioCanciones.ALBUM)) { Album nuevoAlbum = (Album) nuevoRepositorioCanciones; insert = "INSERT INTO albunes (nombre, fechaCreacion, fechaLanzamiento, imagen) VALUES "; insert += "('" + nuevoAlbum.getNombre() + "','"; insert += Date.valueOf(nuevoAlbum.getFechaCreacion()) + "','"; insert += Date.valueOf(nuevoAlbum.getFechaLanzamiento()) + "','"; insert += nuevoAlbum.getImagen() + "')"; } else if (nuevoRepositorioCanciones.getTipoRepo().equals(TipoRepositorioCanciones.LISTA_REPRODUCCION)) { ListaReproduccion nuevaListaReproduccion = (ListaReproduccion) nuevoRepositorioCanciones; insert = "INSERT INTO listasreproduccion (tipoLista, nombre, fechaCreacion, imagen, descripcion) VALUES "; insert += "('" + nuevaListaReproduccion.getTipoLista() + "','"; insert += nuevaListaReproduccion.getNombre() + "','"; insert += Date.valueOf(nuevaListaReproduccion.getFechaCreacion()) + "','"; insert += nuevaListaReproduccion.getImagen() + "','"; insert += nuevaListaReproduccion.getDescripcion() + "')"; } int key = -1; try { Statement query = connection.createStatement(); query.execute(insert, Statement.RETURN_GENERATED_KEYS); ResultSet generatedKeys = query.getGeneratedKeys(); while (generatedKeys.next()) { key = generatedKeys.getInt(1); } } catch (Exception e) { e.printStackTrace(); } return key; } /** * Este método se usa para sobreescribir los datos de un repositorio de canciones en la base de datos * @param RepositorioCancionesActualizado instancia de la clase Repositorio con los cambios aplicados que se desean guardar * @return true si la sobreescritura es correcta, false si ocurre algún error * @throws Exception si no se puede conectar con la DB */ public boolean update(RepositorioCanciones RepositorioCancionesActualizado) throws Exception { String update = ""; if (RepositorioCancionesActualizado.getTipoRepo().equals(TipoRepositorioCanciones.ALBUM)) { Album nuevoAlbum = (Album) RepositorioCancionesActualizado; update = "UPDATE albunes "; update += "SET nombre = '" + nuevoAlbum.getNombre() + "',"; update += "imagen = '" + nuevoAlbum.getImagen() + "'"; update += " WHERE idAlbum = " + nuevoAlbum.getId(); } else if (RepositorioCancionesActualizado.getTipoRepo().equals(TipoRepositorioCanciones.LISTA_REPRODUCCION)) { ListaReproduccion nuevaListaReproduccion = (ListaReproduccion) RepositorioCancionesActualizado; update = "UPDATE listasreproduccion "; update += "SET nombre = '" + nuevaListaReproduccion.getNombre() + "',"; update += "descripcion = '" + nuevaListaReproduccion.getDescripcion() + "',"; update += "imagen = '" + nuevaListaReproduccion.getImagen() + "'"; update += " WHERE idListaReproduccion = " + nuevaListaReproduccion.getId(); } try { Statement query = connection.createStatement(); query.execute(update); return true; } catch (Exception e) { e.printStackTrace(); } return false; } public boolean delete(int idRepositorioCanciones) throws SQLException { RepositorioCanciones repositorioCancionesEncontrado = findByID(idRepositorioCanciones).get(); if(repositorioCancionesEncontrado != null) { String delete = ""; RepositorioCanciones repoEliminar = repositorioCancionesEncontrado; if(repoEliminar.getTipoRepo().equals(TipoRepositorioCanciones.ALBUM)) { delete = "DELETE FROM albunes WHERE idAlbum = " + repoEliminar.getId(); } else if(repoEliminar.getTipoRepo().equals(TipoRepositorioCanciones.BIBLIOTECA)) { delete = "DELETE FROM bibliotecas WHERE idBiblioteca = " + repoEliminar.getId(); } else if(repoEliminar.getTipoRepo().equals(TipoRepositorioCanciones.LISTA_REPRODUCCION)) { delete = "DELETE FROM listasreproduccion WHERE idListaReproduccion = " + repoEliminar.getId(); } try { Statement query = connection.createStatement(); query.execute(delete); return true; } catch (Exception e) { e.printStackTrace(); } } return false; } //General /** * Este método se usa para buscar un repositorio de canciones usando como filtro su id * @param idRepo int que define el id del repositorio de canciones que se desea encontrar * @return objeto de tipo Optional que contiene una instancia de la clase RepositorioCanciones si se encuentra una coincidencia * @throws SQLException si no se puede conectar con la DB o el album no existe */ public Optional<RepositorioCanciones> findByID(int idRepo) throws SQLException { Optional<Album> albumEncontrado = findAlbumById(idRepo); if(albumEncontrado.isPresent()) { return Optional.of(albumEncontrado.get()); } Optional<ListaReproduccion> listaEncontrada = findListaReproduccionById(idRepo); if(listaEncontrada.isPresent()) { return Optional.of(listaEncontrada.get()); } Optional<Biblioteca> bibliotecaEncontrada = findBibliotecaByID(idRepo); if(bibliotecaEncontrada.isPresent()) { return Optional.of(bibliotecaEncontrada.get()); } return null; } //Albunes /** * Este método se usa para obtener una lista con todos los albunes guardados en la base de datos * @return una lista con todos los albunes guardados en la base de datos * @throws SQLException si no se puede conectar con la DB */ public List<Album> findAlbunes() throws SQLException { Statement query = connection.createStatement(); ResultSet result = query.executeQuery("SELECT * FROM albunes"); ArrayList<Album> listaAlbunes = new ArrayList<>(); while (result.next()) { Album albumLeido = new Album(); albumLeido.setId(result.getInt("idAlbum")); albumLeido.setNombre(result.getString("nombre")); albumLeido.setFechaCreacion(result.getDate("fechaCreacion").toLocalDate()); albumLeido.setFechaLanzamiento(result.getDate("fechaLanzamiento").toLocalDate()); albumLeido.setImagen(result.getString("imagen")); albumLeido.setCanciones(buscarCancionesAlbum(albumLeido.getId())); //Agregar canciones al album albumLeido.setArtistas(buscarArtistasAlbum(albumLeido.getId())); //Agregar artistas al album listaAlbunes.add(albumLeido); } return Collections.unmodifiableList(listaAlbunes); } /** * Este método se usa para buscar un album usando como filtro su id * @param idAlbum int que define el id del album que se desea encontrar * @return objeto de tipo Optional que contiene una instancia de la clase Album si se encuentra una coincidencia * @throws SQLException si no se puede conectar con la DB */ public Optional<Album> findAlbumById(int idAlbum) throws SQLException { Statement query = connection.createStatement(); ResultSet result = query.executeQuery("SELECT * FROM albunes WHERE idAlbum = " + idAlbum); while (result.next()) { Album albumLeido = new Album(); albumLeido.setId(result.getInt("idAlbum")); albumLeido.setNombre(result.getString("nombre")); albumLeido.setFechaCreacion(result.getDate("fechaCreacion").toLocalDate()); albumLeido.setFechaLanzamiento(result.getDate("fechaLanzamiento").toLocalDate()); albumLeido.setImagen(result.getString("imagen")); albumLeido.setCanciones(buscarCancionesAlbum(albumLeido.getId())); //Agregar canciones al album albumLeido.setArtistas(buscarArtistasAlbum(albumLeido.getId())); //Agregar artistas al album return Optional.of(albumLeido); } return Optional.empty(); } private ArrayList<Cancion> buscarCancionesAlbum(int pIdAlbum) { try { ArrayList<Cancion> canciones = cancionDAO.findCancionesRepo(pIdAlbum, TipoRepositorioCanciones.ALBUM); return canciones; } catch (Exception e) { e.printStackTrace(); } return new ArrayList<>(); } private ArrayList<Artista> buscarArtistasAlbum(int pIdAlbum) { try { ArrayList<Artista> artistas = artistaDAO.findArtistasAlbum(pIdAlbum); return artistas; } catch (Exception e) { e.printStackTrace(); } return new ArrayList<>(); } //Listas de reproducción /** * Este método se usa para obtener una lista con todas las listas de reproduccion guardadas en la base de datos * @return una lista con todas las listas de reproduccion guardadas en la base de datos * @throws SQLException si no se puede conectar con la DB */ public List<ListaReproduccion> findListasReproduccion() throws SQLException { Statement query = connection.createStatement(); ResultSet result = query.executeQuery("SELECT * FROM listasreproduccion"); ArrayList<ListaReproduccion> listaListasReproduccion = new ArrayList<>(); while (result.next()) { ListaReproduccion listaReproduccionLeida = new ListaReproduccion(); listaReproduccionLeida.setId(result.getInt("idListaReproduccion")); listaReproduccionLeida.setTipoLista(TipoListaReproduccion.valueOf(result.getString("tipoLista"))); listaReproduccionLeida.setNombre(result.getString("nombre")); listaReproduccionLeida.setFechaCreacion(result.getDate("fechaCreacion").toLocalDate()); listaReproduccionLeida.setImagen(result.getString("imagen")); listaReproduccionLeida.setDescripcion(result.getString("descripcion")); listaReproduccionLeida.setCanciones(buscarCancionesLista(listaReproduccionLeida.getId())); //Agregar canciones a la lista listaListasReproduccion.add(listaReproduccionLeida); } return Collections.unmodifiableList(listaListasReproduccion); } /** * Este método se usa para buscar una lista de reproduccion usando como filtro su id * @param idLista int que define el id de la lista de reproduccion que se desea encontrar * @return objeto de tipo Optional que contiene una instancia de la clase ListaReproduccion si se encuentra una coincidencia * @throws SQLException si no se puede conectar con la DB o el album no existe */ public Optional<ListaReproduccion> findListaReproduccionById(int idLista) throws SQLException { Statement query = connection.createStatement(); ResultSet result = query.executeQuery(("SELECT * FROM listasreproduccion WHERE idListaReproduccion = " + idLista)); while (result.next()) { ListaReproduccion listaReproduccionLeida = new ListaReproduccion(); listaReproduccionLeida.setId(result.getInt("idListaReproduccion")); listaReproduccionLeida.setTipoLista(TipoListaReproduccion.valueOf(result.getString("tipoLista"))); listaReproduccionLeida.setNombre(result.getString("nombre")); listaReproduccionLeida.setFechaCreacion(result.getDate("fechaCreacion").toLocalDate()); listaReproduccionLeida.setImagen(result.getString("imagen")); listaReproduccionLeida.setDescripcion(result.getString("descripcion")); listaReproduccionLeida.setCanciones(buscarCancionesLista(listaReproduccionLeida.getId())); //Agregar canciones a la lista return Optional.of(listaReproduccionLeida); } return Optional.empty(); } private ArrayList<Cancion> buscarCancionesLista(int pIdLista) { try { ArrayList<Cancion> canciones = cancionDAO.findCancionesRepo(pIdLista, TipoRepositorioCanciones.LISTA_REPRODUCCION); return canciones; } catch (Exception e) { e.printStackTrace(); } return new ArrayList<>(); } private ArrayList<Cancion> buscarCancionesBiblioteca(int idBiblioteca) { try { ArrayList<Cancion> canciones = cancionDAO.findCancionesRepo(idBiblioteca, TipoRepositorioCanciones.BIBLIOTECA); return canciones; } catch (Exception e) { e.printStackTrace(); } return new ArrayList<>(); } private ArrayList<ListaReproduccion> buscarListasReproduccionBiblioteca(int pIdBiblioteca) { try { String idListas = listasBibliotecaDAO.getIdListasReproduccionBiblioteca(pIdBiblioteca); if(idListas == "") { //No hay listas return new ArrayList<>(); } Statement query = connection.createStatement(); ResultSet result = query.executeQuery("SELECT * FROM listasreproduccion WHERE idListaReproduccion IN (" + idListas + ")"); ArrayList<ListaReproduccion> listaListasReproduccion = new ArrayList<>(); while (result.next()) { ListaReproduccion listaReproduccionLeida = new ListaReproduccion(); listaReproduccionLeida.setId(result.getInt("idListaReproduccion")); listaReproduccionLeida.setTipoLista(TipoListaReproduccion.valueOf(result.getString("tipoLista"))); listaReproduccionLeida.setNombre(result.getString("nombre")); listaReproduccionLeida.setFechaCreacion(result.getDate("fechaCreacion").toLocalDate()); listaReproduccionLeida.setImagen(result.getString("imagen")); listaReproduccionLeida.setDescripcion(result.getString("descripcion")); listaReproduccionLeida.setCanciones(buscarCancionesLista(listaReproduccionLeida.getId())); //Agregar canciones a la lista listaListasReproduccion.add(listaReproduccionLeida); } return listaListasReproduccion; } catch (Exception e) { e.printStackTrace(); } return new ArrayList<>(); } public int getIdLista(String nombre) throws SQLException { Statement query = connection.createStatement(); ResultSet result = query.executeQuery(("SELECT * FROM listasreproduccion WHERE nombre = '" + nombre + "'")); while (result.next()) { int idLista = result.getInt("idListaReproduccion"); return idLista; } return -1; } //Bibliotecas /** * Este método se usa para obtener una lista con todas las bibliotecas guardadas en la base de datos * @return una lista con todas las bibliotecas guardadas en la base de datos * @throws SQLException si no se puede conectar con la DB */ public List<Biblioteca> findBibliotecas() throws SQLException { Statement query = connection.createStatement(); ResultSet result = query.executeQuery("SELECT * FROM bibliotecas"); ArrayList<Biblioteca> listaBibliotecas = new ArrayList<>(); while (result.next()) { Biblioteca bibliotecaLeida = new Biblioteca(); bibliotecaLeida.setId(result.getInt("idBiblioteca")); bibliotecaLeida.setNombre(result.getString("nombre")); bibliotecaLeida.setFechaCreacion(result.getDate("fechaCreacion").toLocalDate()); bibliotecaLeida.setCanciones(buscarCancionesBiblioteca(bibliotecaLeida.getId())); //Agregar canciones a la biblioteca bibliotecaLeida.setListasDeReproduccion(buscarListasReproduccionBiblioteca(bibliotecaLeida.getId())); //Agregar listas de reproduccion a la biblioteca listaBibliotecas.add(bibliotecaLeida); } return Collections.unmodifiableList(listaBibliotecas); } /** * Este método se usa para buscar una biblioteca usando como filtro su id * @param idBiblioteca int que define el id de la biblioteca que se desea encontrar * @return objeto de tipo Optional que contiene una instancia de la clase Biblioteca si se encuentra una coincidencia * @throws SQLException si no se puede conectar con la DB */ public Optional<Biblioteca> findBibliotecaByID(int idBiblioteca) throws SQLException { Statement query = connection.createStatement(); ResultSet result = query.executeQuery(("SELECT * FROM bibliotecas WHERE idBiblioteca = " + idBiblioteca)); while (result.next()) { Biblioteca bibliotecaLeida = new Biblioteca(); bibliotecaLeida.setId(result.getInt("idBiblioteca")); bibliotecaLeida.setNombre(result.getString("nombre")); bibliotecaLeida.setFechaCreacion(result.getDate("fechaCreacion").toLocalDate()); bibliotecaLeida.setCanciones(buscarCancionesBiblioteca(bibliotecaLeida.getId())); //Agregar canciones a la biblioteca bibliotecaLeida.setListasDeReproduccion(buscarListasReproduccionBiblioteca(bibliotecaLeida.getId())); //Agregar listas de reproduccion a la biblioteca return Optional.of(bibliotecaLeida); } return Optional.empty(); } }
756bba3e2f6110fb0574f431a546117b7580ec09
[ "Java", "HTML" ]
13
Java
TaylorSeguraVindas/ProyectoPOO
1e1d9b2055503b25c41ee637886afaff22404778
ed3585d234e23687cbcc6b39213120e7c3e1b5a1
refs/heads/main
<file_sep>import Layout from "components/Layout"; import Link from "next/link"; import Post from "components/Post"; import getPosts from "lib/getPosts"; const HomePage = ({ posts }) => { return ( <Layout> <h1 className="text-4xl border-b-4 p-5 mb-3">Latest Posts</h1> <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-5"> {posts.map(({ slug, ...post }) => ( <Post key={slug} post={{ slug, ...post }} /> ))} </div> <div className="flex justify-center"> <Link href="/blogs"> <button className="w-1/3 px-4 py-3 my-5 border border-gray-500 text-gray-800 rounded-md outline-none focus:ring focus:ring-gray-200 select-none hover:text-white hover:bg-gray-900 transition duration-300 ease-in"> All Posts </button> </Link> </div> </Layout> ); }; export default HomePage; export async function getStaticProps(context) { const posts = getPosts(); return { props: { posts: posts.slice(0, 6) }, }; } <file_sep>import { useMemo, useRef, useState } from "react"; import debounce from "lodash/debounce"; import SearchIcon from "../icons/search.svg"; import SearchResults from "./SearchResults"; const Search = () => { const searchRef = useRef(null); const [searchResult, setSearchResult] = useState([]); const getResults = useMemo( () => debounce(async term => { const res = await fetch(`/api/search?q=${term.toLowerCase()}`); const results = await res.json(); setSearchResult(results); }, 1000), [] ); const handleChange = () => { if (searchRef.current.value === "") return setSearchResult([]); getResults(searchRef.current.value); }; return ( <div className="bg-gray-600 px-2 py-4 sm:px-4 relative"> <div className="flex items-center justify-center md:justify-end"> <div className="w-full md:w-1/3 flex justify-between items-center px-2 py-3 bg-gray-200 rounded-full mr-3 text-gray-600 text-sm focus-within:bg-white"> <input ref={searchRef} type="search" placeholder="Search Posts..." className="outline-none bg-transparent flex-1" onChange={handleChange} /> <SearchIcon className="h-5 w-5" /> </div> </div> {searchRef.current?.value && ( <SearchResults results={searchResult} /> )} </div> ); }; export default Search; <file_sep>import getPosts from "lib/getPosts"; export default async function handler(req, res) { let posts = []; const searchTerm = req.query.q; if (process.env.NODE_ENV === "production") { // Fetch from cache as for static site api runs as serverless fn and cannot read/write to/from files const { posts: cachedPosts } = await import("../../cache/data"); posts = cachedPosts; } else { posts = getPosts(); } const results = posts.filter( ({ title, category, excerpt }) => title.toLowerCase().includes(searchTerm) || excerpt.toLowerCase().includes(searchTerm) || category.toLowerCase().includes(searchTerm) ); res.status(200).json(results); } <file_sep>export const sortbyDate = (d1, d2) => new Date(d2.date) - new Date(d1.date); <file_sep>import CategoryLabel from "components/CategoryLabel"; import Layout from "components/Layout"; import fs from "fs"; import matter from "gray-matter"; import Link from "next/link"; import Image from "next/image"; import path from "path"; import marked from "marked"; const BlogPage = ({ frontmatter, content, slug }) => { const { title, category, date, cover_image, author, author_image } = frontmatter; return ( <Layout title={`${title} - ${author}`}> <div className="mx-6"> <Link href="/blogs"> <a className="text-sky-500 hover:text-blue-600 font-medium text-lg flex items-center space-x-1"> <span className="text-2xl">&#129044;</span>{" "} <p>Go Back</p> </a> </Link> <div className="w-full px-10 py-6 bg-white rounded-lg shadow-md mt-6"> <div className="flex items-center justify-between mt-3"> <h1 className="text-5xl mb-6">{title}</h1> <CategoryLabel>{category}</CategoryLabel> </div> <div className="w-full h-[650px] relative"> <Image src={cover_image} layout="fill" objectFit="cover" className="rounded" alt="Cover Image" /> </div> <div className="flex items-center justify-between bg-gray-100 rounded-md px-3 py-2 mt-7"> <div className="flex items-center space-x-3"> <div className="h-10 w-10 relative hidden sm:block"> <Image src={author_image} layout="fill" objectFit="cover" className="rounded-full" alt="Author Image" /> </div> <h3 className="text-indigo-600 font-semibold"> {author} </h3> </div> <p className="text-sm text-gray-600">{date}</p> </div> <div className="mt-4 blog-body"> <div dangerouslySetInnerHTML={{ __html: marked(content), }} /> </div> </div> </div> </Layout> ); }; export async function getStaticPaths() { const files = fs.readdirSync(path.join("posts")); const paths = files.map(fileName => ({ params: { slug: fileName.replace(".md", "") }, })); return { paths, fallback: false, }; } export async function getStaticProps({ params }) { const { data: frontmatter, content } = matter.read( path.join("posts", `${params.slug}.md`) ); return { props: { frontmatter, content, slug: params.slug, }, }; } export default BlogPage; <file_sep>import fs from "fs"; import matter from "gray-matter"; import path from "path"; import { sortbyDate } from "utils/"; const getPosts = () => { const files = fs.readdirSync(path.join("posts")); const posts = files.map(fileName => { const slug = fileName.replace(".md", ""); const { data: frontmatter } = matter.read(path.join("posts", fileName)); return { slug, ...frontmatter }; }); return posts.sort(sortbyDate); }; export default getPosts; <file_sep>import CategoryLabel from "./CategoryLabel"; import Link from "next/link"; import Image from "next/image"; const Post = ({ post, compact = false }) => { return ( <div className="px-7 py-6 bg-white shadow-md rounded-md my-4 border border-gray-200 mx-2"> {!compact && ( <Image src={post.cover_image} width={600} height={420} className="rounded" alt="Cover Image" /> )} <div className="flex justify-between items-center mt-3"> <span className="font-light text-gray-600 text-sm"> {post.date} </span> <CategoryLabel>{post.category}</CategoryLabel> </div> <div className="mt-2"> <Link href={`/blogs/${post.slug}`}> <a className="text-2xl text-gray-700 font-bold hover:underline"> {post.title} </a> </Link> <p className="mt-2 text-gray-600">{post.excerpt}</p> </div> {!compact && ( <div className="mt-4 flex justify-between items-center"> <Link href={`/blogs/${post.slug}`}> <a className="text-gray-500 hover:text-blue-600"> Read More </a> </Link> <div className="sm:flex items-center"> <div className="h-10 w-10 relative hidden sm:block mr-4"> <Image src={post.author_image} alt={post.author} className="rounded-full" layout="fill" objectFit="cover" /> </div> <h3 className="text-gray-700 font-bold"> {post.author} </h3> </div> </div> )} </div> ); }; export default Post; <file_sep>import Link from "next/link"; const CategoryList = ({ categories, activeCategory }) => { return ( <div className="w-full p-5 bg-white rounded-lg shadow-md mt-6"> <h3 className="text-2xl bg-gray-700 text-white p-3 rounded"> Blog Categories </h3> <ul className="divide-y divide-gray-300"> {categories.map(category => ( <Link key={category} href={`/blogs/category/${category.toLowerCase()}`}> <li className={`p-4 cursor-pointer rounded ${ activeCategory === category.toLowerCase() ? "bg-indigo-400 text-white font-bold" : "hover:bg-blue-50" }`}> {category} </li> </Link> ))} </ul> </div> ); }; export default CategoryList; <file_sep>[![wakatime](https://wakatime.com/badge/github/raunak96/devspace-static-blog.svg)](https://wakatime.com/badge/github/raunak96/devspace-static-blog) # DevSpace - Static Blog Site (NextJs + TailwindCss + Markdown) ![DevSpace Blog](/public/images/app-demo.png 'DevSpace Blog') [VIEW DEMO](https://rawn-blog.vercel.app/) ## Getting Started Clone this repository and then run the following commands: ```bash npm i npm run dev # or yarn yarn dev ``` ### Parsing Frontmatter in Markdown files Using package [gray-matter](https://github.com/jonschlinkert/gray-matter). ### Parsing Markdown Content to HTML > Using package [marked](https://github.com/markedjs/marked). - The html then injected to page using dangerouslySetInnerHTML prop provided by React. ### SERVING STATIC SITE LOCALLY > We use the [serve](https://github.com/vercel/serve) package for this. - In [package.json](/package.json), do the following in scripts: `build: next build && next export` - Before running the above script to export static HTML, see to the following: - If we are using **next/image** Image component for Image Optimisation, `next export` will not work. To make sure, it does ,we can do the following: - Configure a third party loader like **cloudinary**. Docs [here](https://nextjs.org/docs/basic-features/image-optimization). - Use html **img** instead. - Deploy to **Vercel** which takes care of everything automatically. - Now run the following command: ```bash yarn build ``` - Then you'll have a static version of your app in the **out** directory. - Finally serve the static site using: ```bash serve -s out ``` ### Caching Data for Search because it calls our API route **/api/search** client side as we type in search box (Refer these [docs](https://medium.com/@matswainson/building-a-search-component-for-your-next-js-markdown-blog-9e75e0e7d210)) - In NextJs, api routes behave as serverless functions when deployed so they cannot use fileSystem(fileReaders and writers), hence we cannot directly read and parse data from markdown files and resond with this result unlike getStaticProps which is run server side(in NodeJs) which can use filesystem. - For this, we make a **script** ( [/scripts/cache.js](/scripts/cache.js) ), which we will run before committing the code (**pre-commit**) - This script will parse all markdown files and write that data in another file ( [/cache/data.js](cache/data.js) ) in a constant which is also exported. - Now in API handler, we can simply import the constant from the cache which has the data and return it after processing it. ### Setting Up Automatic caching before every git commit using [husky](https://www.npmjs.com/package/husky) package - We add a **pre-commit** git hook using **husky** which in our case parses the markdown files and stores them in cache ( [/cache/data.js](cache/data.js) ) as explained above using the following command: ```bash npx husky add .husky/pre-commit "yarn cache-blogs && git add cache/data.js" ``` - The git add command is done because the `yarn cache-blogs` will make changes to said file so we need to stage it in this hook.<file_sep>export const BLOGS_PER_PAGE = 6; <file_sep>import Link from "next/link"; import { useCallback } from "react"; const CategoryLabel = ({ children }) => { const colorKey = useCallback(() => { const colorCode = { javascript: "yellow", css: "blue", python: "green", php: "purple", ruby: "red", }; return children.toLowerCase() in colorCode ? `bg-${colorCode[children.toLowerCase()]}-600` : "bg-indigo-600"; }, []); return ( <div className={`px-2 py-1 text-gray-100 ${colorKey()} font-bold rounded`}> <Link href={`/blogs/category/${children.toLowerCase()}`}> {children} </Link> </div> ); }; export default CategoryLabel; <file_sep>import Post from "./Post"; const SearchResults = ({ results }) => { return ( <div className="search-modal absolute top-20 right-1/2 translate-x-1/2 md:right-2 md:translate-x-0 w-3/4 md:w-1/2 lg:w-2/5 z-40 border-4 border-gray-300 border-r-0 bg-white text-black rounded-2xl h-auto max-h-[500px] overflow-y-auto"> <div className="p-10"> <h2 className="text-2xl mb-2"> {results.length} Result{results.length !== 1 && "s"} </h2> {results.map(post => ( <Post key={post.slug} post={post} compact /> ))} </div> </div> ); }; export default SearchResults;
bfa3d44640ccd4c9448870f55cdbadd59ebdef6a
[ "JavaScript", "Markdown" ]
12
JavaScript
raunak96/devspace-static-blog
c7386670b144a599a75e35739504e4b8d02f6d16
133619da8ad09b7f1575dfbf5f0d81bae2618263
refs/heads/master
<file_sep>import pandas as pd class write_excel: # Метод для сохранения данных в data.xlsx def write_excel(list_product, list_features, list_money): # Запись в словарь,через функцию DataFrame book = pd.DataFrame({ 'Продукт': list_product, 'Модели': list_features, 'Цена (руб)': list_money, }) # Записываем данные в data.xlsx writer = pd.ExcelWriter('data.xlsx') book.to_excel(writer) writer.save() <file_sep># Инструкция для разработчика # Если вы запустили первый раз PyChar # Нужно установить библиотек: 1)lxml 2)requests 3)Beautifulsoup4 4)pandas # Пример - pip install requests # Библиотеки import requests from bs4 import BeautifulSoup # Классы, которыми пользуемся в Main from write_txt import write_txt from write_excel import write_excel # Ocновной класс class Parsing: # Пустой метод def __init__(self): pass # Переменные # URL - ссылка на сайт, response - сохраняем данные, soup - помещаем текст ответа URL = 'https://iotvega.com/product' response = requests.get(URL) soup = BeautifulSoup(response.text, 'lxml') # Теги, которые хотим парсить div_product_name = soup.find_all('div', class_='product-name') div_product_items = soup.find_all('a', class_='main-container') # Ключевые слова, по которым ищем информацию в features = i.find('ul').text.strip() search_word = ('Датчик', 'датчик', 'базовая станция', 'Базовая станция') # Счётчик для сохранения данных в write_txt count = 0 # Списки в которые будут записываться данные с тегов list_product = [] list_features = [] list_money = [] # Списки для сохранения в словарь и файл write_txt "data.txt" ready_dictionary = {} ready_list = [] # Цикл всех тегов на сайте for n, i in enumerate(div_product_items, start=1): # Запись тегов в переменные product = i.find('h2').text features = i.find('ul').text.strip() money = i.find('span').text.strip() # Цикл на проверку ключевых слов for word in range(len(search_word)): # Цикл перебора слов из списка search_word if features.find(search_word[word]) != -1: # Условия, чтобы не выводилась информация с money if money == 'Снято с продажи' or money == 'Цена по запросу': pass else: # Добавление данных в списки list_product.append(product) list_features.append(features) list_money.append(money) list_money.sort() count += 1 # Вызовов метода из класса write_txt write_txt.write_txt(list_product, list_features, list_money, count, ready_dictionary) # Вызовов метода из класса write_excel write_excel.write_excel(list_product, list_features, list_money) <file_sep>class write_txt: # Метод, для добавления информации в data.txt def write_txt(list_product, list_features, list_money, count, ready_dictionary): # Открываем файл with open('data.txt', 'a') as f: # Цикл для записи в словарь данных for i in range(count): # Запись в словарь ready_dictionary = ({ 'Продукст - ': list_product[i], 'Модель - ': list_features[i], 'Цена (руб) - ': int(list_money[i]), }) # Запись в файл data.txt f.write(f'{ready_dictionary}''\n')
0721e8134da4dd1863f201c56fe218223bd28cd2
[ "Python" ]
3
Python
DerasezRus/ParsingONNIP
9961ad1cad06df59f431aaa3be1c7a4f3ec99b81
f13d727094a1db9c6451714f4410fe5b711e5ad8
refs/heads/master
<file_sep>import os import requests from flask import Flask, render_template, request from flask_socketio import SocketIO, emit app = Flask(__name__) # app.config["SECRET_KEY"] = os.getenv("SECRET_KEY") socketio = SocketIO(app) lst = [] votes = {"yes":0, "no":0, "maybe":0} @app.route("/") def index(): return render_template("index.html", votes=votes) @socketio.on("submit vote") def vote(data): selection = data["selection"] votes[selection] += 1 emit("vote totals", votes, broadcast=True) if __name__ == '__main__': #app.debug = True #app.run(host = '0.0.0.0',port=8900) socketio.run(app, host='0.0.0.0', port=8900)
3408dd58d7703f81abaa84572e9db2c61e4aa9cb
[ "Python" ]
1
Python
drjquang/Lecture_5_JavaScript
a9c75d0bc546c43cb196e8be423f44456ffee1f9
f9ab5a5047464eab68c526d5ac97e6f7c5470090
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestMarrow.Configuration { internal class PropertyConfig { internal String ParsingTemplate { get; set; } } } <file_sep>using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using TestMarrow; using System.Collections.Generic; namespace FedoroffSoft.TestMarrow.UnitTest.StructureWithScalarProps { [TestClass] public class StructureWithScalarProps { [TestMethod] public void SimpleObject() { String str = @">| Name | Value | Key | CreatedOn | | Marrow | 13.07 | 27 | 2018-03-15 |"; var parser = new MarrowParser(); var struct1 = parser.Parse<Struct1>(str); Assert.AreEqual("Marrow", struct1.Name, "Name parsing failed"); Assert.AreEqual(13.07, struct1.Value, "Value parsing failed"); Assert.AreEqual(27, struct1.Key, "Key parsing failed"); Assert.AreEqual(new DateTime(2018,03,15), struct1.CreatedOn, "CreatedOn parsing failed"); } [TestMethod] public void SimpleList() { String str = @">| Name | Value| Key | CreatedOn | | Ma rrow | 13.07| 0 | 2017-03-15| | Marrow 1 | 13 | -123| 2018-03-15| | Marrow one two| -16 | 56 | 2019-03-15| "; var parser = new MarrowParser(); var struct1 = parser.Parse<List<Struct1>>(str); Assert.AreEqual("Ma rrow" , struct1[0].Name , "Name parsing failed for line 0"); Assert.AreEqual(13.07 , struct1[0].Value , "Value parsing failed for line 0"); Assert.AreEqual(0 , struct1[0].Key , "Key parsing failed for line 0"); Assert.AreEqual(new DateTime(2017,03,15) , struct1[0].CreatedOn , "CreatedOn parsing failed for line 0"); Assert.AreEqual("<NAME>" , struct1[1].Name , "Name parsing failed for line 1"); Assert.AreEqual(13 , struct1[1].Value , "Value parsing failed for line 1"); Assert.AreEqual(-123 , struct1[1].Key , "Key parsing failed for line 1"); Assert.AreEqual(new DateTime(2018,03,15) , struct1[1].CreatedOn , "CreatedOn parsing failed for line 1"); Assert.AreEqual("<NAME>" , struct1[2].Name , "Name parsing failed for line 2"); Assert.AreEqual(-16 , struct1[2].Value , "Value parsing failed for line 2"); Assert.AreEqual(56 , struct1[2].Key , "Key parsing failed for line 2"); Assert.AreEqual(new DateTime(2019,03,15) , struct1[2].CreatedOn , "CreatedOn parsing failed for line 2"); } } public class Struct1 { public string Name { get; set; } public Double Value { get; set; } public int Key { get; set; } public DateTime CreatedOn { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestMarrow { /// <summary> /// This an auxiliary class to store the current data during the recursive parsing of a string /// </summary> internal class ParsingContext { internal List<String> SourceLines { get; set; } internal int LineIndex { get; set; } internal int StructLevel { get; set; } internal MetaInfo MetaInfo { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace TestMarrow.Configuration { public class ClassConfig<T> { private Dictionary<String, PropertyConfig> classConfig; private String curProperty; internal ClassConfig(Dictionary<String, PropertyConfig> classConfig) { this.classConfig = classConfig; } public ClassConfig<T> ConfigureProperty(Expression<Func<T, object>> expr) { MemberExpression memberExpression = null; if (expr.NodeType == ExpressionType.Lambda) { var body = (UnaryExpression) expr.Body; memberExpression = body.Operand as MemberExpression; curProperty = memberExpression.Member.Name; } else throw new ArgumentException("Property is expected", "expr"); return this; } } } <file_sep>using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using TestMarrow; namespace FedoroffSoft.TestMarrow.UnitTest.SimpleConfigTest { [TestClass] public class SimpleConfigTest { [TestMethod] public void TestSimpleConfig() { String str = @">| Name | Value | Key | CreatedOn | | Marrow | 13.07 | 27 | 2018-03-15 |"; var parser = new MarrowParser(); parser.ConfigureClass<Struct1>() .ConfigureProperty(s => s.Key); var struct1 = parser.Parse<Struct1>(str); Assert.AreEqual("Marrow", struct1.Name, "Name parsing failed"); Assert.AreEqual(13.07, struct1.Value, "Value parsing failed"); Assert.AreEqual(27, struct1.Key, "Key parsing failed"); Assert.AreEqual(new DateTime(2018,03,15), struct1.CreatedOn, "CreatedOn parsing failed"); } } public class Struct1 { public string Name { get; set; } public Double Value { get; set; } public int Key { get; set; } public DateTime CreatedOn { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace TestMarrow { /// <summary> /// Stores info about a parced meta line. For example such line: /// >| strcutProp1 | Name | Value | /// /// </summary> internal class MetaInfo { /// <summary> /// The name of the property. It's used when we analys the type of a property that belongs to a class /// </summary> internal String PropName { get; set; } /// <summary> /// Indicates that the property is a collection /// </summary> internal bool IsCollection { get; set; } /// <summary> /// The type of the property we analyse. If the propery is a collection then here's the type of the collection item. /// </summary> internal Type PropType { get; set; } /// <summary> /// The properties names extracted from the header lines. /// </summary> internal String[] SubPropNames { get; set; } internal PropertyInfo[] SubPropInfo { get; set; } internal Boolean FirstLine { get; set; } = false; } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using TestMarrow.Configuration; namespace TestMarrow { public class MarrowParser { private readonly Dictionary<String, Dictionary<String, PropertyConfig>> config; public String NullValue { get; set; } = "NULL"; public String EmptyStringValue { get; set; } = @""""; public MarrowParser() { config = new Dictionary<String, Dictionary<String, PropertyConfig>>(); } public T Parse<T>(String str) where T: class, new() { T result = null; ParsingContext context = new ParsingContext(); //Let's convert the source string into array of lines to iterate through them context.SourceLines = new List<String>(); String line = null; using (StringReader sr = new StringReader(str)) while( (line = sr.ReadLine()) != null) context.SourceLines.Add(line); //The first line is alway a meta data for the first leve class MetaInfo parentInfo = CheckCollectionClass(typeof(T), new MetaInfo()); parentInfo.FirstLine = true; var metaInfo = ParseMetaLine(parentInfo, context.SourceLines[0]); //Now we start the recursive processing of the lines //Let's process the rest of the lines context.StructLevel = 0; context.LineIndex = 1; context.MetaInfo = metaInfo; result = ParseLevel<T>(context); return result; } /// <summary> /// The methos parces the data for one level. It uses recursion to parse sub-levels /// </summary> /// <typeparam name="T"></typeparam> /// <param name="level">The current level in the test structures</param> /// <param name="sourceLines">The string array that contains the source lines of the data</param> /// <param name="lineIndex">The zero-based index of the currently processing line in the source lines</param> /// <param name="metaInfo">The meta info about the class the current line must be parsed to</param> /// <returns></returns> internal T ParseLevel<T>(ParsingContext context) where T: class, new() { //Let's check if the T class is onle of supported collections T result = new T(); Type listType = null; //The IEnumerable classes are supported. if (context.MetaInfo.IsCollection) { //we use the List type of generic enumerable collections Type listTypeBase = typeof(List<>); Type[] typeArgs = { context.MetaInfo.PropType }; listType = listTypeBase.MakeGenericType(typeArgs); result = (T)Activator.CreateInstance(listType); } Boolean isPropLine = false; //the object to work with a single item; Object item = null; while(context.LineIndex < context.SourceLines.Count()) { string line = context.SourceLines[context.LineIndex]; if (String.IsNullOrWhiteSpace(line)) { context.LineIndex++; continue; } line = line.Trim(); //Let's check if the current line is a start for a complex property that contains the properties //such lines must start with the '>' sign isPropLine = line.Substring(0,1) == ">"; //We encounter with the sub-structure - one of the class propery is not a scalar one if(isPropLine) { var subMetaInfo = ParseMetaLine(context.MetaInfo, line); //Let's use the recursion to parse it. var curLevelMetaInfo = context.MetaInfo; var curLevelStructLevel = context.StructLevel; MethodInfo method = ((TypeInfo)(this.GetType())).DeclaredMethods.First(t => t.Name == "ParseLevel"); MethodInfo generic = null; if(subMetaInfo.IsCollection) { var genericList = typeof(List<>).MakeGenericType(subMetaInfo.PropType); generic = method.MakeGenericMethod(genericList); } else { generic = method.MakeGenericMethod(subMetaInfo.PropType); } //Create context for the call context.LineIndex++; context.StructLevel++; context.MetaInfo = subMetaInfo; var subResult = generic.Invoke(this, new [] { context }); //Restore context after the call context.StructLevel = curLevelStructLevel; context.MetaInfo = curLevelMetaInfo; //let's assing the result to the item object PropertyInfo prop = context.MetaInfo.SubPropInfo.First(p => p.Name.Equals(subMetaInfo.PropName)); prop.SetValue(item, subResult); } else { //Let's check that the current level from the function argument matches the current level in the data line String[] rawValues = line.Split('|').Select(s => s.Trim()).ToArray(); //we have to discard the data before the first '|' character and data after the last one rawValues = rawValues.Skip(1).Take(rawValues.Count() - 2).ToArray(); int lineLevel = 0; for ( ; lineLevel < rawValues.Count(); lineLevel++) if (!String.IsNullOrWhiteSpace(rawValues[lineLevel])) break; //This line belongs to the upper level class. We don't have to process it if (lineLevel < context.StructLevel) break; //Les't create and object instance to work with for every new data line item = Activator.CreateInstance(context.MetaInfo.PropType); //We need data for the level specified in the argument var strValues = rawValues.Skip(context.StructLevel).Take(rawValues.Count() - context.StructLevel).ToArray(); for (int i = 0; i < strValues.Count(); i++) { if (!context.MetaInfo.SubPropInfo.Any(p => p.Name.Equals(context.MetaInfo.SubPropNames[i]))) throw new ArgumentException($"The property '{context.MetaInfo.SubPropNames[i]}' is absent in the '{context.MetaInfo.PropType.Name}' class"); PropertyInfo prop = context.MetaInfo.SubPropInfo.First(p => p.Name.Equals(context.MetaInfo.SubPropNames[i])); //Standart type conversion Object value = null; if (prop.PropertyType.Name == "String" && strValues[i].Equals(EmptyStringValue, StringComparison.InvariantCulture)) value = String.Empty; else if (strValues[i].Equals(NullValue, StringComparison.InvariantCulture)) value = null; else value = Convert.ChangeType(strValues[i], prop.PropertyType); //Let's update the property with the value. prop.SetValue(item, value); } if (context.MetaInfo.IsCollection) { //we know that the result is a List and has the Add method MethodInfo addMethod = listType.GetMethod("Add"); object magicValue = addMethod.Invoke(result, new[] { item }); } //Line is processed context.LineIndex++; } } //for a non-collection type we return the object item. if( !context.MetaInfo.IsCollection ) result = (T)item; return result; } /// <summary> /// parces the infor about property line. For example, such lines /// >| strcutProp1 | Name | Value | /// </summary> /// <typeparam name="T">The type of the parent class</typeparam> /// <param name="level">Level in the string data</param> /// <param name="line">raw text of the line</param> /// <returns></returns> private MetaInfo ParseMetaLine(MetaInfo parentInfo, String line) { var result = new MetaInfo(); var rawProps = line .Replace(">", String.Empty) .Split('|') .Where(s => ! String.IsNullOrWhiteSpace(s))//ignore empty names on the left and right sides of the source string. Note, it's assumend that a property name can't be empty! .Select(s => s.Trim()); //For the first level, the prop type was already parsed if (parentInfo.FirstLine) { result.PropType = parentInfo.PropType; result.IsCollection = parentInfo.IsCollection; //The names of the properties specified in the test data result.SubPropNames = rawProps.ToArray(); } else { //For the non-first levels, we have to extract data form the parent class and the line //the name of the complex property result.PropName = rawProps.First(); PropertyInfo prop = parentInfo.PropType.GetProperties().FirstOrDefault(p => p.Name.Equals(result.PropName)); if(prop == null) throw new ArgumentException($"The property {result.PropName} is absent in the {result.PropType.Name} class"); result = CheckCollectionClass(prop.PropertyType, result); //The names of the properties specified in the test data //we skip the property name in the parent class result.SubPropNames = rawProps.Skip(1).ToArray(); } //lets check that we will be able to create instances of the item type if (result.PropType.GetConstructor(Type.EmptyTypes) == null) throw new ArgumentException($"The generic type '{result.PropType.Name}' has to have a parameterless constructor."); result.SubPropInfo = result.PropType.GetProperties(); return result; } private MetaInfo CheckCollectionClass(Type type, MetaInfo meta) { meta.IsCollection = typeof(IEnumerable).IsAssignableFrom(type); //If the type is a collection then we need the item type if (meta.IsCollection) { //actually we need the collection item type. //We support the collections of only one generic type Type[] genericTypes = type.GetGenericArguments(); if (genericTypes.Count() != 1) throw new ArgumentException("currently TestMarrow supports collection of only one generic type"); meta.PropType = genericTypes[0]; } else meta.PropType = type; return meta; } public ClassConfig<T> ConfigureClass<T>() where T: class { String className = typeof(T).Name; if (!config.Keys.Contains(className)) config.Add(className, new Dictionary<string, PropertyConfig>()); return new ClassConfig<T>(config[className]); } } } <file_sep>using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using TestMarrow; using System.Collections.Generic; using KellermanSoftware.CompareNetObjects; namespace FedoroffSoft.TestMarrow.UnitTest.CollectionWithSubStruct { [TestClass] public class CollectionWithSubStruct { [TestMethod] public void OneLineTestData() { String str = @">| Name1 | Value1 | | Marrow | 13.07 | >| StrcutProp1 | Name2 | Value2 | | | SubMarrow | 0 | | Marrow 3 | -12 | "; var parser = new MarrowParser(); var actual = parser.Parse<List<Struct1>>(str); var expected = new List<Struct1> { new Struct1 { Name1 = "Marrow", Value1 = 13.07, StrcutProp1 = new Struct2 { Name2 = "SubMarrow", Value2 = 0 } }, new Struct1 { Name1 = "<NAME>", Value1 = -12 } }; CompareLogic compareLogic = new CompareLogic(); ComparisonResult result = compareLogic.Compare(actual, expected); if (!result.AreEqual) throw new Exception( result.DifferencesString ); } [TestMethod] public void MultyLineSubPropData() { String str = @">| Name1 | Value1 | | Marrow | 13.07 | >| EnumStrcutProp1 | Name2 | Value2 | | | SubMarrow1 | 4 | | | SubMarrow2 | 5 | | NULL | -12 | | "" | -.43 | "; var parser = new MarrowParser(); var actual = parser.Parse<List<Struct1>>(str); var expected = new List<Struct1> { new Struct1 { Name1 = "Marrow", Value1 = 13.07, EnumStrcutProp1 = new List<Struct2> { new Struct2 {Name2 = "SubMarrow1", Value2 = 4 }, new Struct2 {Name2 = "SubMarrow2", Value2 = 5 }, } }, new Struct1 { Value1 = -12 }, new Struct1 { Name1 = String.Empty, Value1 = -0.43 } }; CompareLogic compareLogic = new CompareLogic(); compareLogic.Config.IgnoreCollectionOrder = true; ComparisonResult result = compareLogic.Compare(actual, expected); if (!result.AreEqual) throw new Exception( result.DifferencesString ); } } public class Struct1 { public string Name1 { get; set; } public Double Value1 { get; set; } public Struct2 StrcutProp1 { get; set; } public IEnumerable<Struct2> EnumStrcutProp1 { get; set; } } public class Struct2 { public string Name2 { get; set; } public Double Value2 { get; set; } } } <file_sep># TestMarrow **Note that the project doesn't have a stable version yet. Necessary functionality is not implemented and not tested yet.** A library to simplify the test data composing in the source code of tests. When you need fill a complex structures for a test then you have to write something like this using C#: var expected = new List<Struct1> { new Struct1 { Name1 = "Marrow", Value1 = 13.07, EnumStrcutProp1 = new List<Struct2> { new Struct2 {Name2 = "SubMarrow1", Value2 = 4 }, new Struct2 {Name2 = "SubMarrow2", Value2 = 5 }, } }, new Struct1 { Value1 = -12 }, new Struct1 { Name1 = String.Empty, Value1 = -0.43 } }; TestMarrow allows you to create the same object using this syntax: String str = @">| Name1 | Value1 | | Marrow | 13.07 | >| EnumStrcutProp1 | Name2 | Value2 | | | SubMarrow1 | 4 | | | SubMarrow2 | 5 | | NULL | -12 | | "" | -.43 | "; var parser = new MarrowParser(); var actual = parser.Parse<List<Struct1>>(str); <file_sep>using System; using System.Text; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using TestMarrow; namespace FedoroffSoft.TestMarrow.UnitTest.StructWithSubstruct { /// <summary> /// Here we test the parsing of a structire that besides the scalar properties has other structures but not collections /// </summary> [TestClass] public class StructureWithSubstructures { [TestMethod] public void SimpleObjectWithSubObjects() { String str = @">| Name1 | Value1 | | Marrow | 13.07 | >| strcutProp1 | Name2 | Value2 | | | SubMarrow | 0 | "; var parser = new MarrowParser(); var struct1 = parser.Parse<Struct1>(str); Assert.AreEqual("Marrow", struct1.Name1, "Name parsing failed"); Assert.AreEqual(13.07, struct1.Value1, "Value parsing failed"); Assert.AreEqual("SubMarrow", struct1.strcutProp1.Name2, "strcutProp1.Value parsing failed"); Assert.AreEqual(0, struct1.strcutProp1.Value2, "strcutProp1.Value parsing failed"); } } public class Struct1 { public string Name1 { get; set; } public Double Value1 { get; set; } public Struct2 strcutProp1 { get; set; } } public class Struct2 { public string Name2 { get; set; } public Double Value2 { get; set; } } }
b1becd95598ac2522ccb975c1798332a7f577b0a
[ "Markdown", "C#" ]
10
C#
FedoroffSoft/TestMarrow
47c49ac5a1f170941f78cba266c8bb8650b713ff
45130da8e024d8e225e7777fc83ece4930f22281
refs/heads/master
<repo_name>christianbleske/Kapitel13<file_sep>/UniversalBsp/UniversalBsp/ViewController.swift // // ViewController.swift // UniversalBsp // // Created by <NAME> on 11.03.15. // Copyright (c) 2015 <NAME>. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var uiImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() let screenSize: CGRect = UIScreen.main.nativeBounds let screenWidth = screenSize.width let screenHeight = screenSize.height print("Width=\(screenWidth)") print("Height=\(screenHeight)") switch (screenHeight) { case 960: self.uiImageView.image = UIImage(named: "background-960@2x.png")! break; case 1136: self.uiImageView.image = UIImage(named: "background-1136@2x.png")! break; case 1334: self.uiImageView.image = UIImage(named: "background-1334@2x.png")! break; case 2208: self.uiImageView.image = UIImage(named: "background-2208@3x.png")! break; case 1024: self.uiImageView.image = UIImage(named: "background-1024.png")! break; case 2048: self.uiImageView.image = UIImage(named: "background-2048@2x.png")! break; default: break; } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func button_Pressed(_ sender: AnyObject) { if UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad { self.showAlertViewWithTitle("Neues Spiel", message: "iPad-Version...") } if UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.phone { self.showAlertViewWithTitle("Ne<NAME>", message: "iPhone-Version...") } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { if UIDevice.current.orientation.isLandscape { print("Landscape-Mode") } else { print("Portrait-Mode") } } func showAlertViewWithTitle(_ title:String, message:String) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let OKAction = UIAlertAction(title: "OK", style: .default) { (action) in // ... } alertController.addAction(OKAction) self.present(alertController, animated: true) { // ... } } }
7b78417c8607595352cef33a34f67cd73e990604
[ "Swift" ]
1
Swift
christianbleske/Kapitel13
f28315bf1701a4a4773cc1046cabe72209c03ea9
90a4d30e214fd83e0a4970bbe138567110912395
refs/heads/master
<repo_name>thaihx/Laravel-pthreads<file_sep>/app/Console/Commands/SimplePool.php <?php declare(strict_types = 1); namespace App\Console\Commands; use Illuminate\Console\Command; /** * Class SimplePool * @package App\Console\Commands * @author <NAME> <<EMAIL>> */ final class SimplePool extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'simplepool'; /** * The console command description. * * @var string */ protected $description = 'Command description'; /** * Execute the console command. * * @return mixed */ public function handle() { $pool = new DeployPool(1); $pool->submitJob(new DeployJob('Boo')); } } class DeployPool extends \Pool { public function __construct($size) { parent::__construct($size, DeployWorker::class, []); } public function submitJob(DeployJob $deployJob) { parent::submit(new DeployRunner($deployJob)); } } class DeployWorker extends \Worker { public function run() { } } class DeployRunner extends \Collectable { /** @var DeployJob */ private $deployJob; /** * DeployRunner constructor. * @param DeployJob $ */ public function __construct(DeployJob $deployJob) { $this->deployJob = $deployJob; } public function run() { echo "Hello World\n"; $sleep = rand(1, 5); echo "Sleeping for {$sleep}" . PHP_EOL; time_nanosleep($sleep, 0); echo "Bye World\n"; $this->setGarbage(); } } class DeployJob { private $message; /** * DeployJob constructor. * @param $message */ public function __construct($message) { $this->message = $message; } /** * @return mixed */ public function getMessage() : string { return $this->message; } } <file_sep>/simplepool.php <?php class DeployPool extends Pool { public function __construct($size) { parent::__construct($size, DeployWorker::class, []); } public function submitJob(DeployJob $deployJob) { parent::submit(new DeployRunner($deployJob)); } } class DeployWorker extends Worker { public function run() { } } class DeployRunner extends Collectable { /** @var DeployJob */ private $deployJob; /** * DeployRunner constructor. * @param DeployJob $ */ public function __construct(DeployJob $deployJob) { $this->deployJob = $deployJob; } public function run() { echo "Hello World\n"; $sleep = rand(1, 3); echo "Sleeping for {$sleep}" . PHP_EOL; time_nanosleep($sleep, 0); echo "Bye World\n"; $this->setGarbage(); } } class DeployJob { private $message; /** * DeployJob constructor. * @param $message */ public function __construct($message) { $this->message = $message; } /** * @return mixed */ public function getMessage() : string { return $this->message; } } $pool = new DeployPool(4); for ($i = 0; $i < 8; $i++) { $pool->submitJob(new DeployJob('Boo')); } while ($pool->collect( function (Collectable $task) { return $task->isGarbage(); } )) { continue; } $pool->shutdown(); <file_sep>/readme.md ``` git clone <EMAIL>:mrsimonbennett/Laravel-pthreads.git cd Laravel-pthreads composer install php simplepool.php php artisan simplepool ```
640d00259cf2b9e3d88dbf2ca2432100c04f317b
[ "Markdown", "PHP" ]
3
PHP
thaihx/Laravel-pthreads
7818760d5388260e365eba4f7f1f7d57a3b73ed6
42e48a342b8435143bfee37d8d67794c855d5e24
refs/heads/main
<file_sep># SE_Assignment This repo is a part of SE lab assignment. <file_sep>def summ(args): if isinstance(args, (int, float)): return args elif isinstance(args, (dict, str)): return "Invalid Input" total = 0 try: for value in args: total += value return total except TypeError: return "Invalid Input" testing_set = [[15,'me'], {"a":58, "b":9}, 10, [78, 899, 67264], (537, 4823, 49732), 972.5, [121.12, 232.2, 898.7, 87], "COEP"] check = 1 for each_case in testing_set: print("Testing for ", each_case) if isinstance(each_case, int) or isinstance(each_case, float): s = each_case else: try: s = sum(each_case) except TypeError: s = "Invalid Input" assert summ(each_case) == s, "Condition failed" print("Condition{} OK\n". format(check)) check = check + 1
e5741df2d012ada5353296fdb4479ce21095be6f
[ "Markdown", "Python" ]
2
Markdown
HimanshGupta10/SE_Assignment
80971166c91c4e3b12b8265c939e628d87255390
f3bf22ef0faba39178dfdd009a7bed81480d5881
refs/heads/master
<file_sep>#!/usr/bin/python ############################################################################# # Licensed Materials - Property of HCL* # (C) Copyright HCL Technologies Ltd. 2017, 2018 All rights reserved. # * Trademark of HCL Technologies Limited ############################################################################# import waconn import argparse import datetime # ----------------------------------------------------- # Define and parse command line arguments # ----------------------------------------------------- parser = argparse.ArgumentParser(description='Change the availability of a resource in TWSz plan') parser.add_argument('-e','--engineName', help='name of the engine as defined in the TWSz Connector', required=True, metavar="<engine_name>") parser.add_argument('-r','--resName', help='resource name filter', required=True, metavar="<resource_name_filter>") parser.add_argument('-a','--avail', help='availability yes/no', required=True, metavar="yes|no") parser.add_argument('-n','--howMany', help='max numer of returned job streams', required=False, metavar="<how_many>") args = parser.parse_args() howMany = '100' if args.howMany: howMany=args.howMany # ----------------------------------------------------- # Intialize the client utility module # ----------------------------------------------------- conn = waconn.WAConn('waconn.ini','/twsz/v1/'+args.engineName) # ----------------------------------------------------- # Query the plan and get the resource ids # ----------------------------------------------------- resp = conn.post('/plan/current/resource/query', json={"filters": {"resourceInPlanFilter": {"resourceName": args.resName}}}, headers={'How-Many': howMany}) r = resp.json() if len(r) == 0: print('resource not found') exit(2) # ----------------------------------------------------- # Change availability of all resources # ----------------------------------------------------- for res in r: print ("Changing availability for "+res["resourceInPlanKey"]["name"]) response = conn.get('/plan/current/resource/'+res["id"]) res = response.json() print (res) print ("current overridden availability: "+res["defaultConstraints"]["isAvailable"]) # Set overriddenAvailability and save res["defaultConstraints"]["isAvailable"] = "YES" if (args.avail == 'yes') else "NO" print ("new overridden availability: "+res["defaultConstraints"]["isAvailable"]) res = conn.put('/plan/current/resource/'+res["id"],json=res) print (res) <file_sep>############################################################################# # Licensed Materials - Property of HCL* # (C) Copyright HCL Technologies Ltd. 2017, 2018 All rights reserved. # * Trademark of HCL Technologies Limited ############################################################################# import ConfigParser import base64 def readProps(inifile): pwd='' user='' hosts=[] config = ConfigParser.SafeConfigParser(allow_no_value=True) config.read(inifile) if not config.has_section('WASERVER'): raise Exception(inifile + " must have connection properties in WASERVER section") if config.has_option('WASERVER', 'pwd'): pwd=config.get('WASERVER', 'pwd') enc=base64.b64encode(pwd) config.remove_option('WASERVER', 'pwd') config.set('WASERVER', '; pwd = <PASSWORD>') config.set('WASERVER', 'key', enc); with open(inifile, 'wb') as configfile: config.write(configfile) elif config.has_option('WASERVER', 'key'): enc=config.get('WASERVER', 'key') pwd=base64.b64decode(enc) if config.has_option('WASERVER', 'user'): user=config.get('WASERVER', 'user') if config.has_option('WASERVER', 'hosts'): rawhosts=config.get('WASERVER', 'hosts'); hosts=rawhosts.split(",") if config.has_option('WASERVER', 'verify'): rawVerify=config.get('WASERVER', 'verify'); verify=(rawVerify.lower == 'true') props={'user' : user, 'pwd' : pwd, 'hosts': hosts, 'verify': verify} return props <file_sep>#!/usr/bin/python ############################################################################# # Licensed Materials - Property of HCL* # (C) Copyright HCL Technologies Ltd. 2017, 2018 All rights reserved. # * Trademark of HCL Technologies Limited ############################################################################# import waconn import argparse import datetime import time # ----------------------------------------------------- # Define and parse command line arguments # ----------------------------------------------------- parser = argparse.ArgumentParser(description='Change the time dependency of a job in TWSz plan') parser.add_argument('-e','--engineName', help='name of the engine as defined in the TWSz Connector', required=True, metavar="<engine_name>") parser.add_argument('-j','--jsName', help='jobstream name filter', required=True, metavar="<jobstream_name_filter>") parser.add_argument('-n','--howMany', help='max numer of returned job streams', required=False, metavar="<how_many>") args = parser.parse_args() howMany = '100' if args.howMany: howMany=args.howMany # ----------------------------------------------------- # Intialize the client utility module # ----------------------------------------------------- conn = waconn.WAConn('waconn.ini','/twsz/v1/'+args.engineName) # ----------------------------------------------------- # Query the plan and get the job ids # ----------------------------------------------------- resp = conn.post('/plan/current/job/query', json={"filters": {"jobInPlanFilter": {"jobStreamName": args.jsName}}}, headers={'How-Many': howMany}) r = resp.json() if len(r) == 0: print('job not found') exit(2) print ("Length of the list of job that matches this filter is",len(r)) # ----------------------------------------------------- # GET JOBS AND SAVE JOBLOGS # ----------------------------------------------------- for job in r: print ("GETTING JOBLOG FOR JOB "+job["name"]+" in JOBSTREAM "+job["jobStreamInPlan"]["name"]+" IA = "+job["jobStreamInPlan"]["startTime"]) response = conn.get('/plan/current/job/'+job["id"]+'/joblog') joblog = response.json() # NOTE: THIS PATH MUST EXIST joblog_path = "D:/joblog/" if not (response.status_code == 200): for j in joblog["messages"]: if ("EQQM637I" in j or "EQQM391I" in j): time.sleep(10) response = conn.get('/plan/current/job/'+job["id"]+'/joblog') joblog = response.json() file=open(joblog_path + job["jobStreamInPlan"]["name"]+"_"+job["jobStreamInPlan"]["startTime"]+"_"+job["name"]+".txt","w+") log = joblog["log"] file.write(log) file.close() print ("YOU CAN FIND YOUR JOBLOG HERE: " + joblog_path)<file_sep>############################################################################# # Licensed Materials - Property of HCL* # (C) Copyright HCL Technologies Ltd. 2017, 2018 All rights reserved. # * Trademark of HCL Technologies Limited ############################################################################# from .conn import WAConn <file_sep>#!/usr/bin/python ############################################################################# # Licensed Materials - Property of HCL* # (C) Copyright HCL Technologies Ltd. 2017, 2018 All rights reserved. # * Trademark of HCL Technologies Limited ############################################################################# import waconn import argparse import datetime # ----------------------------------------------------- # Define and parse command line arguments # ----------------------------------------------------- parser = argparse.ArgumentParser(description='List job streams in TWSz plan') parser.add_argument('-e','--engineName', help='name of the engine as defined in the TWSz Connector', required=True, metavar="<engine_name>") parser.add_argument('-j','--jsName', help='job stream', required=True, metavar="<job_stream_name>") parser.add_argument('-n','--howMany', help='max numer of returned job streams', required=False, metavar="<how_many>") args = parser.parse_args() howMany = '100' if args.howMany: howMany=args.howMany # ----------------------------------------------------- # Intialize the client utility module # ----------------------------------------------------- conn = waconn.WAConn('waconn.ini','/twsz/v1/'+args.engineName) # ----------------------------------------------------- # Query the model and get the js id # ----------------------------------------------------- resp = conn.post('/plan/current/jobstream/query', json={"filters": {"jobStreamInPlanFilter ": {"jobStreamName": args.jsName}}}, headers={'How-Many': howMany}) r = resp.json() if len(r) == 0: print('job stream not found') exit(2) # ----------------------------------------------------- # Print result # ----------------------------------------------------- for js in r: print (js["key"]["name"]+" - "+js["key"]["startTime"]) <file_sep>#!/usr/bin/python ############################################################################# # Licensed Materials - Property of HCL* # (C) Copyright HCL Technologies Ltd. 2017, 2018 All rights reserved. # * Trademark of HCL Technologies Limited ############################################################################# import waconn import argparse import datetime # ----------------------------------------------------- # Define and parse command line arguments # ----------------------------------------------------- parser = argparse.ArgumentParser(description='Run a WAPL command') parser.add_argument('-e','--engineName', help='name of the engine as defined in the TWSz Connector', required=True, metavar="<engine_name>") parser.add_argument('-c','--cmds', help='WAPL command to run', required=True, metavar="<cmds>") args = parser.parse_args() now = datetime.datetime.utcnow().isoformat() # ----------------------------------------------------- # Intialize the client utility module # ----------------------------------------------------- conn = waconn.WAConn('waconn.ini','/twsz/v1/'+args.engineName) # ----------------------------------------------------- # Query the model and get the js id # ----------------------------------------------------- resp = conn.textPost('/wapl', text=args.cmds) r = resp.content if len(r) == 0: print('no response') exit(2) # ----------------------------------------------------- # Print result # ----------------------------------------------------- print (r) <file_sep>[WASERVER] hosts = https://10.14.49.87:16311 user = smadmin verify = false ; pwd = <PASSWORD> key = <KEY>= <file_sep>#!/usr/bin/python ############################################################################# # Licensed Materials - Property of HCL* # (C) Copyright HCL Technologies Ltd. 2017, 2018 All rights reserved. # * Trademark of HCL Technologies Limited ############################################################################# import waconn import argparse import datetime # ----------------------------------------------------- # Define and parse command line arguments # ----------------------------------------------------- parser = argparse.ArgumentParser(description='Submit a job stream to the TWSz plan') parser.add_argument('-e','--engineName', help='name of the engine as defined in the TWSz Connector', required=True, metavar="<engine_name>") parser.add_argument('-j','--jsName', help='job stream', required=True, metavar="<job_stream_name>") parser.add_argument('-w','--hold', help='hold parameter true/false', required=True, metavar="<hold_param>") args = parser.parse_args() now = datetime.datetime.utcnow().isoformat() # ----------------------------------------------------- # Intialize the client utility module # ----------------------------------------------------- conn = waconn.WAConn('waconn.ini','/twsz/v1/'+args.engineName) # ----------------------------------------------------- # Submit the jobstream to the plan # ----------------------------------------------------- submit = {"name": args.jsName, "startTime": now, "holdAll":args.hold} # now we can submit the js print "submit parameters: " +str(submit) resp = conn.post('/plan/current/jobstream/action/add_jobstream', json=submit) r = resp.json() for js in r: print ('Submitted: '+js) <file_sep>############################################################################# # Licensed Materials - Property of HCL* # (C) Copyright HCL Technologies Ltd. 2017, 2018 All rights reserved. # * Trademark of HCL Technologies Limited ############################################################################# import requests import uuid from .prop import readProps import logging from httplib import HTTPConnection #HTTPConnection.debuglevel = 1 logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests logging.getLogger().setLevel(logging.DEBUG) requests_log = logging.getLogger("requests.packages.urllib3") requests_log.setLevel(logging.DEBUG) requests_log.propagate = True class WAConn: reqId = str(uuid.uuid4()) config = {} prefix = '' hostIdx = 0 def __init__(self, propFile, pref): self.config = readProps(propFile) self.prefix = pref def __str__(self): return 'WAConn (%s, %s)' % (self.config, self.prefix) def request(self, method, uri, headers=None, params=None, json=None, data=None): headers = headers or {} if 'Content-Type' not in headers: headers['Content-Type'] = 'application/json' if 'Accept' not in headers: headers['Accept'] = 'application/json' if 'How-Many' not in headers: headers['How-Many'] = '500' if 'Request-Id' not in headers: headers['Request-Id'] = self.reqId retry = True hosts = self.config['hosts'] retries = 0 resp = None skipError = False while retry and retries < len(hosts): retry = False url = hosts[self.hostIdx] + self.prefix + uri print 'Connecting to %s for %s' % (url, method) try: resp = requests.request(method, url, json=json, data=data, headers=headers, auth=(self.config['user'],self.config['pwd']), verify=self.config['verify']) except requests.exceptions.ConnectionError, error: print 'Connection error: '+ str(error) retry = True self.hostIdx+=1 if self.hostIdx >= len(hosts): self.hostIdx=0 retries+=1 if resp is None: raise StandardError('Error connecting host',resp) print 'Result: %d' % resp.status_code if not (resp.status_code == 200 or resp.status_code == 201 or resp.status_code == 202): try: j = resp.json() print j["exceptionName"] for m in j["messages"]: if ("EQQM637I" in m or "EQQM391I" in m): skipError = True print m except ValueError: print resp.content print (resp.status_code) if (skipError == False): raise StandardError('%s %s : %s' % (method, url, resp.status_code)) return resp def put(self, uri, json=None, headers=None): return self.request('PUT', uri, headers=headers, json=json) def post(self, uri, json=None, headers=None): return self.request('POST', uri, headers=headers, json=json) def textPost(self, uri, text=None, headers=None): headers = headers or {} if 'Content-Type' not in headers: headers['Content-Type'] = 'text/plain' if 'Accept' not in headers: headers['Accept'] = 'text/plain' return self.request('POST', uri, headers=headers, data=text) def get(self, uri, params=None,headers=None): return self.request('GET', uri, headers=headers, params=params) <file_sep># TWSzOS_REST_API_Python_samples This repository contains Python Rest API samples for TWSzOS. Swagger documentation of the REST APIs is available on your DWC server: https://<dwc hostname>/twsz/ [List jobstream definitions](https://github.com/WorkloadAutomation/TWSzOS_REST_API_Python_samples/blob/master/python/list_jobstreams.py) [List resource definitions](https://github.com/WorkloadAutomation/TWSzOS_REST_API_Python_samples/blob/master/python/list_resources.py) [List jobstreams in plan](https://github.com/WorkloadAutomation/TWSzOS_REST_API_Python_samples/blob/master/python/list_jobstreams_inplan.py) [Submit jobstream](https://github.com/WorkloadAutomation/TWSzOS_REST_API_Python_samples/blob/master/python/submit_jobstream.py) [Submit jobstream by ID](https://github.com/WorkloadAutomation/TWSzOS_REST_API_Python_samples/blob/master/python/submit_jobstream_byid.py) [Submit jobstream on Hold](https://github.com/WorkloadAutomation/TWSzOS_REST_API_Python_samples/blob/master/python/submit_jobstream_on_hold.py) [WAPL](https://github.com/WorkloadAutomation/TWSzOS_REST_API_Python_samples/blob/master/python/wapl.py)
aee7ce1c303c397c54afae4de721c92351aa1d16
[ "Markdown", "Python", "INI" ]
10
Python
WorkloadAutomation/TWSzOS_REST_API_Python_samples
da332ce2e19b189a8d2a20901a55ed1a3310a47b
83fc825cb824cceca3a91aa3664d2e30a7390ed6
refs/heads/main
<file_sep>document.getElementById('result-count').textContent = ''; document.getElementById('error-msg').style.display = 'none'; document.getElementById('spin').style.display = 'none'; const searchTeam = () => { const searchText = document.getElementById('searchText'); const text = searchText.value; searchText.value = ''; if (text == '') { displayError(); } else { document.getElementById('result-count').textContent = ''; document.getElementById('error-msg').style.display = 'none'; document.getElementById('spin').style.display = 'block'; const url = `https://www.thesportsdb.com/api/v1/json/1/searchteams.php?t=${text}`; fetch(url) .then(res => res.json()) .then(data => displayResult(data.teams)); } } const displayError = () => { document.getElementById('result-count').textContent = ''; document.getElementById('error-msg').style.display = 'block'; document.getElementById('spin').style.display = 'none'; document.getElementById('search-result').textContent = ""; } const displayResult = teams => { const searchResult = document.getElementById('search-result'); searchResult.textContent = ''; if (teams == null) { displayError(); } else { document.getElementById('spin').style.display = 'none'; document.getElementById('result-count').innerText = `Total Found ${teams.length}`; teams.forEach(team => { const div = document.createElement('div'); div.classList.add('col'); div.innerHTML = ` <div class="card h-100 border-3 border-danger w-75"> <img src="${team.strTeamLogo}" class="card-img-top" alt=""> <div class="card-body"> <h5 class="card-title">${team.strTeam}</h5> <p class="card-text">${team.strLeague} </p> <p class="card-text">${team.strStadiumLocation} </p> </div> <div class="card-footer fw-400 text-warning"> <button onclick = loadTeamDetails('${team.idTeam}') class="btn bg-warning fw-400 text-white" type="button" id="button-addon2">Load Details</button> </div> </div> `; searchResult.appendChild(div) }) } } const loadTeamDetails = teamId => { console.log(teamId) const url = `https://www.thesportsdb.com/api/v1/json/1/lookupteam.php?id=${teamId}`; fetch(url) .then(res => res.json()) .then(data => showTeamDetails(data.teams[0])); } const showTeamDetails = team => { console.log(team); const detailsDiv = document.getElementById('detail'); detailsDiv.textContent = ""; const div = document.createElement('div'); div.innerHTML = ` <div class="card"> <img src="${team.strStadiumThumb}" class="card-img-top" alt=""> <div class="card-body "> <h5 class="card-title">${team.strLeague}</h5> <h5 class="card-title">${team.strCountry}</h5> <p class="card-text">${team.strLeague}</p> <p class="card-text">${team.strStadiumLocation}</p> <p class="card-text">${team.strDescriptionEN.slice(0, 150)}</p> <a href="${team.strYoutube}" class="btn btn-warning">Go Youtube</a> </div> </div> ` detailsDiv.appendChild(div); }
0bf9dc32e5cafceb19b24db4680eff852703bc31
[ "JavaScript" ]
1
JavaScript
Magferat/Sports-DB
2676c62f9486ed280fe8ac45389fea1b7fade8e9
777876438d0ace4cb1d0aa55b7988c0aa4bafcde
refs/heads/master
<repo_name>paragkhodke72/RealEstateManagementSystem<file_sep>/newproject 2/src/main/java/com/mycompany/newproject/UserController.java package com.mycompany.newproject; import java.io.IOException; import java.net.URL; import java.security.Principal; import java.security.acl.LastOwnerException; import java.security.acl.NotOwnerException; import java.security.acl.Owner; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.DialogPane; import javafx.scene.control.MenuButton; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.stage.Stage; public class UserController implements Initializable{ @FXML private TextField et_search; @FXML private ComboBox<String> menu_city; @FXML private ComboBox<String> menu_state; @FXML private ComboBox<String> menu_country; @FXML private Button btn_search; @FXML private TableView<Property> property_table; @FXML private TableColumn<Property, String> propertyName; @FXML private TableColumn<Property, String> propertyType; @FXML private TableColumn<Property, String> propertyAddress; @FXML private TableColumn<Property, String> noOfBedsCol; @FXML private TableColumn<Property, String> sqFtCol; @FXML private TableColumn<Property, String> ownerCol; @FXML private TableColumn<Property, String> statusCol; @FXML private TableColumn<Property, String> priceCol; @FXML private MenuButton menu_type; @FXML private Button switchToSelling; @FXML private Button dashboardButton; @FXML private Button propertyButton; @FXML private Button propertyTypeButton; @FXML private Button myPropertiesButton; @FXML private Button logoutButton; @FXML private Button ownerButton; @FXML private Button inquiryButton; static List<Property> propertyList = new ArrayList<Property>(); @FXML void dashboard(ActionEvent event) throws IOException { App.setRoot("UserDashboard"); } @FXML void inquiry(ActionEvent event) throws IOException { App.setRoot("UserInquiries"); } @FXML void listProperties(ActionEvent event) throws IOException { App.setRoot("UserPropertyList"); } @FXML void logout(ActionEvent event) throws IOException { App.setRoot("Login"); } @FXML void myProperty(ActionEvent event) throws IOException { App.setRoot("UserBoughtProperties"); } @FXML void ownerList(ActionEvent event) throws IOException { App.setRoot("EditProfile"); } @FXML void propertyType(ActionEvent event) throws IOException { App.setRoot("UserPropertyTypes"); } @FXML void switchToSelling(ActionEvent event) throws IOException { App.setRoot("SellerDashboard"); } @FXML void searchProperty(ActionEvent event) { String name = et_search.getText().toString(); String city = menu_city.getSelectionModel().getSelectedItem().toString(); String state = menu_state.getSelectionModel().getSelectedItem().toString(); String country = menu_country.getSelectionModel().getSelectedItem().toString(); LoginController controller = new LoginController(); String id = controller.getId(); ConnectionClass connectionClass = new ConnectionClass(); Connection connection = connectionClass.getConnection(); String query1 = "SELECT city,state,country,address,name,type,status,price,sq_feet,no_of_beds from properties where name=? or city=?"; PreparedStatement preparedStmt1; try { preparedStmt1 = connection.prepareStatement(query1); preparedStmt1.setString(1, name); preparedStmt1.setString(2, city); ResultSet resultSet = preparedStmt1.executeQuery(); ObservableList row = FXCollections.observableArrayList(); while (resultSet.next()) { for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) { row.add(resultSet.getString(i).toString()); System.out.println(row); } // data.add(row); } List<Property> properties = new ArrayList<Property>(); for(int i =0 ; i<row.size();i++){ Property property = new Property(); String city1 =row.get(i).toString(); i++; String state1=row.get(i).toString(); i++; String country1=row.get(i).toString(); i++; property.setLocation(row.get(i).toString()+","+city1+","+state1+","+country1); i++; property.setPropertyName(row.get(i).toString()); i++; property.setType(row.get(i).toString()); i++; property.setStatus(row.get(i).toString()); i++; property.setPrice(row.get(i).toString()); i++; property.setSquareFeetArea(row.get(i).toString()); i++; property.setNoOfBeds(row.get(i).toString()); properties.add(property); } ObservableList<Property> stateObservable =FXCollections.observableArrayList(properties); propertyName.setCellValueFactory(new PropertyValueFactory<Property, String>("propertyName")); propertyAddress.setCellValueFactory(new PropertyValueFactory<Property, String>("location")); propertyType.setCellValueFactory(new PropertyValueFactory<Property, String>("type")); sqFtCol.setCellValueFactory(new PropertyValueFactory<Property, String>("squareFeetArea")); statusCol.setCellValueFactory(new PropertyValueFactory<Property, String>("status")); priceCol.setCellValueFactory(new PropertyValueFactory<Property, String>("price")); noOfBedsCol.setCellValueFactory(new PropertyValueFactory<Property, String>("noOfBeds")); property_table.setItems(stateObservable); connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void initialize(URL arg0, ResourceBundle arg1) { try { setCountryBox(); setCityBox(); setStateBox(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void setCountryBox() throws SQLException{ ConnectionClass connectionClass = new ConnectionClass(); Connection connection = connectionClass.getConnection(); String query1 = "SELECT name from countries"; PreparedStatement preparedStmt1; try { preparedStmt1 = connection.prepareStatement(query1); ResultSet resultSet = preparedStmt1.executeQuery(); ObservableList row = FXCollections.observableArrayList(); while (resultSet.next()) { for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) { row.add(resultSet.getString(i).toString()); System.out.println(row); } // data.add(row); } this.menu_country.setItems(row); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } connection.close(); } public void setStateBox() throws SQLException{ ConnectionClass connectionClass = new ConnectionClass(); Connection connection = connectionClass.getConnection(); String query1 = "SELECT name from states"; PreparedStatement preparedStmt1; try { preparedStmt1 = connection.prepareStatement(query1); ResultSet resultSet = preparedStmt1.executeQuery(); ObservableList row = FXCollections.observableArrayList(); while (resultSet.next()) { for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) { row.add(resultSet.getString(i).toString()); System.out.println(row); } // data.add(row); } this.menu_state.setItems(row); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } connection.close(); } public void setCityBox() throws SQLException{ ConnectionClass connectionClass = new ConnectionClass(); Connection connection = connectionClass.getConnection(); String query1 = "SELECT name from cities"; PreparedStatement preparedStmt1; try { preparedStmt1 = connection.prepareStatement(query1); ResultSet resultSet = preparedStmt1.executeQuery(); ObservableList row = FXCollections.observableArrayList(); while (resultSet.next()) { for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) { row.add(resultSet.getString(i).toString()); System.out.println(row); } // data.add(row); } this.menu_city.setItems(row); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } connection.close(); } } <file_sep>/newproject 2/src/main/java/com/mycompany/newproject/SignupController.java package com.mycompany.newproject; import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import java.util.Timer; import java.util.TimerTask; import javax.swing.JOptionPane; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.control.Button; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.stage.Modality; import javafx.stage.Stage; public class SignupController implements Initializable { @FXML private ImageView slideShow; @FXML private TextField firstNameFeild; @FXML private PasswordField passwordfeild; @FXML private TextField lastNameFeild; @FXML private TextField ageFeild; @FXML private TextField emailFeild; @FXML private Button signupBtn; @FXML private Button backBtn; public int count = 0; @FXML void goBack(ActionEvent event) throws IOException { App.setRoot("Login"); } @FXML void signUp(ActionEvent event) throws SQLException { String firstName = firstNameFeild.getText().toString(); String lastName = lastNameFeild.getText().toString(); String age = ageFeild.getText().toString(); String email = emailFeild.getText().toString(); String password = <PASSWORD>().<PASSWORD>(); ConnectionClass connectionClass = new ConnectionClass(); Connection connection = connectionClass.getConnection(); String query = "insert into users (first_name, last_name, email, age, role,password)" + " values (?, ?, ?, ?, ?,?)"; String query1 = "insert into user_details (email, password, role)" + " values (?, ?, ?)"; PreparedStatement preparedStmt = connection.prepareStatement(query); PreparedStatement preparedStmt1 = connection.prepareStatement(query1); preparedStmt1.setString(1, email); preparedStmt1.setString(2, password); preparedStmt1.setString(3, "user"); preparedStmt.setString(1, firstName); preparedStmt.setString(2, lastName); preparedStmt.setString(3, email); preparedStmt.setString(4, age); preparedStmt.setString(5, "user"); preparedStmt.setString(6, password); preparedStmt.execute(); preparedStmt1.execute(); connection.close(); Alert a = new Alert(AlertType.NONE); a.setAlertType(AlertType.INFORMATION); // set content text a.setContentText("SignUp Successful!\n Your UserName is "+firstName+"_"+lastName); // show the dialog a.show(); try { Thread.sleep(2000); } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } a.close(); try { App.setRoot("Login"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void initialize(URL location, ResourceBundle resources) { firstNameFeild.setStyle("-fx-text-fill: white; -fx-font-size: 18px; -fx-background-color:#000000;-fx-border-color: #0078D7"); lastNameFeild.setStyle("-fx-text-fill: white; -fx-font-size: 18px; -fx-background-color:#000000;-fx-border-color: #0078D7"); emailFeild.setStyle("-fx-text-fill: white; -fx-font-size: 18px; -fx-background-color:#000000;-fx-border-color: #0078D7"); ageFeild.setStyle("-fx-text-fill: white; -fx-font-size: 18px; -fx-background-color:#000000;-fx-border-color: #0078D7"); passwordfeild.setStyle("-fx-text-fill: white; -fx-font-size: 18px; -fx-background-color:#000000;-fx-border-color: #0078D7"); Image image = new Image("com/mycompany/newproject/images/background9.jpg"); Image image1 = new Image("com/mycompany/newproject/images/background12.jpg"); Image image2= new Image("com/mycompany/newproject/images/background23.jpg"); Image image3 = new Image("com/mycompany/newproject/images/background24.jpg"); Image image4 = new Image("com/mycompany/newproject/images/background25.jpg"); List<Image> imageArrayList = new ArrayList<Image>(); imageArrayList.add(image1); imageArrayList.add(image); imageArrayList.add(image2); imageArrayList.add(image3); imageArrayList.add(image4); // then in your method long delay = 2000; //update once per 2 seconds. new Timer().schedule(new TimerTask() { @Override public void run() { slideShow.setImage(imageArrayList.get(count++)); if (count >= imageArrayList.size()) { count = 0; } } }, 0, delay); } } <file_sep>/newproject 2/src/main/java/com/mycompany/newproject/UserPropertyTypeController.java package com.mycompany.newproject; import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; public class UserPropertyTypeController implements Initializable{ @FXML private TableView<PropertyType> property_table; @FXML private TableColumn<PropertyType,String> propertyName; @FXML private Button switchToSelling; @FXML private Button logoutButton; @FXML private Button inquiryButton; @FXML private Button ownerButton; @FXML private Button myPropertiesButton; @FXML private Button propertyTypeButton; @FXML private Button propertyButton; @FXML private Button dashboardButton; @FXML void dashboard(ActionEvent event) throws IOException { App.setRoot("UserDashboard"); } @FXML void inquiry(ActionEvent event) throws IOException { App.setRoot("UserInquiries"); } @FXML void listProperties(ActionEvent event) throws IOException { App.setRoot("UserPropertyList"); } @FXML void logout(ActionEvent event) throws IOException { App.setRoot("Login"); } @FXML void myProperty(ActionEvent event) throws IOException { App.setRoot("UserBoughtProperties"); } @FXML void ownerList(ActionEvent event) throws IOException { App.setRoot("EditProfile"); } @FXML void propertyType(ActionEvent event) throws IOException { App.setRoot("UserPropertyTypes"); } @FXML void switchToSelling(ActionEvent event) throws IOException { App.setRoot("SellerDashboard"); } @Override public void initialize(URL arg0, ResourceBundle arg1) { ConnectionClass connectionClass = new ConnectionClass(); Connection connection = connectionClass.getConnection(); String query1 = "SELECT name from property_types"; PreparedStatement preparedStmt1; try { preparedStmt1 = connection.prepareStatement(query1); ResultSet resultSet = preparedStmt1.executeQuery(); ObservableList row = FXCollections.observableArrayList(); while (resultSet.next()) { for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) { row.add(resultSet.getString(i).toString()); System.out.println(row); } // data.add(row); } List<PropertyType> types = new ArrayList<PropertyType>(); for(int i =0 ; i<row.size();i++){ PropertyType type = new PropertyType(); type.setType(row.get(i).toString()); types.add(type); } ObservableList<PropertyType> propertyTypeObservable =FXCollections.observableArrayList(types); propertyName.setCellValueFactory(new PropertyValueFactory<PropertyType, String>("type")); property_table.setItems(propertyTypeObservable); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>/newproject 2/src/main/java/com/mycompany/newproject/PropertyType.java package com.mycompany.newproject; import java.util.List; public class PropertyType extends Property { private String type; public PropertyType() { super(); // TODO Auto-generated constructor stub } public PropertyType(String propertyName, String location, String owner, String status, String description, String noOfBeds, String type, String squareFeetArea, String price, List<String> amenities) { super(propertyName, location, owner, status, description, noOfBeds, type, squareFeetArea, price, amenities); // TODO Auto-generated constructor stub } public String getType() { return type; } public void setType(String type) { this.type = type; } } <file_sep>/README.md # RealEstateManagementSystem Standalone project with java, JavaFX, MySql, Scenebuilder <file_sep>/newproject 2/src/main/java/com/mycompany/newproject/UserBoughtPropertiesController.java package com.mycompany.newproject; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.sql.Blob; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import javax.imageio.ImageIO; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.embed.swing.SwingFXUtils; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.image.Image; public class UserBoughtPropertiesController implements Initializable{ @FXML private Button viewButton; @FXML private Button switchToSelling; @FXML private TableView<Property> property_table; @FXML private TableColumn<Property, String> nameCol; @FXML private TableColumn<Property, String> typeCol; @FXML private TableColumn<Property, String> addressCol; @FXML private TableColumn<Property, String> bedsCol; @FXML private TableColumn<Property, String> sq_feetCol; @FXML private TableColumn<Property, String> status; @FXML private TableColumn<Property, String> price; @FXML private Button logoutButton1; @FXML private Button inquiryButton1; @FXML private Button ownerButton1; @FXML private Button myPropertiesButton1; @FXML private Button propertyTypeButton1; @FXML private Button propertyButton1; @FXML private Button dashboardButton1; static List<Property> propertyList = new ArrayList<Property>(); private static Property property = new Property(); @FXML void View(ActionEvent event) throws IOException { this.property = this.property_table.getSelectionModel().getSelectedItem(); UserPropertyListController controller = new UserPropertyListController(); controller.setProperty(this.property); System.out.println(property.getPropertyName()); App.setRoot("ViewProperty"); } @FXML void dashboard(ActionEvent event) throws IOException { App.setRoot("UserDashboard"); } @FXML void inquiry(ActionEvent event) throws IOException { App.setRoot("UserInquiries"); } @FXML void listProperties(ActionEvent event) throws IOException { App.setRoot("UserPropertyList"); } @FXML void logout(ActionEvent event) throws IOException { App.setRoot("Login"); } @FXML void myProperty(ActionEvent event) throws IOException { App.setRoot("UserBoughtProperties"); } @FXML void ownerList(ActionEvent event) throws IOException { App.setRoot("EditProfile"); } @FXML void propertyType(ActionEvent event) throws IOException { App.setRoot("UserPropertyTypes"); } @FXML void switchToSelling(ActionEvent event) throws IOException { App.setRoot("SellerDashboard"); } @Override public void initialize(URL location, ResourceBundle resources) { LoginController controller = new LoginController(); String id = controller.getId(); ConnectionClass connectionClass = new ConnectionClass(); Connection connection = connectionClass.getConnection(); String query1 = "SELECT city,state,country,address,name,type,status,price,sq_feet,no_of_beds from properties where buyer_id =?"; PreparedStatement preparedStmt1; try { preparedStmt1 = connection.prepareStatement(query1); preparedStmt1.setString(1, id); ResultSet resultSet = preparedStmt1.executeQuery(); ObservableList row = FXCollections.observableArrayList(); while (resultSet.next()) { for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) { row.add(resultSet.getString(i).toString()); System.out.println(row); } // data.add(row); } List<Property> properties = new ArrayList<Property>(); for(int i =0 ; i<row.size();i++){ Property property = new Property(); String city =row.get(i).toString(); i++; String state=row.get(i).toString(); i++; String country=row.get(i).toString(); i++; property.setLocation(row.get(i).toString()+","+city+","+state+","+country); i++; property.setPropertyName(row.get(i).toString()); i++; property.setType(row.get(i).toString()); i++; property.setStatus(row.get(i).toString()); i++; property.setPrice(row.get(i).toString()); i++; property.setSquareFeetArea(row.get(i).toString()); i++; property.setNoOfBeds(row.get(i).toString()); properties.add(property); } ObservableList<Property> stateObservable =FXCollections.observableArrayList(properties); nameCol.setCellValueFactory(new PropertyValueFactory<Property, String>("propertyName")); addressCol.setCellValueFactory(new PropertyValueFactory<Property, String>("location")); typeCol.setCellValueFactory(new PropertyValueFactory<Property, String>("type")); sq_feetCol.setCellValueFactory(new PropertyValueFactory<Property, String>("squareFeetArea")); status.setCellValueFactory(new PropertyValueFactory<Property, String>("status")); price.setCellValueFactory(new PropertyValueFactory<Property, String>("price")); bedsCol.setCellValueFactory(new PropertyValueFactory<Property, String>("noOfBeds")); property_table.setItems(stateObservable); connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public Property getViewProperty(){ return this.property; } } <file_sep>/newproject 2/src/main/java/com/mycompany/newproject/SellerProfileController.java package com.mycompany.newproject; import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.control.Alert.AlertType; public class SellerProfileController implements Initializable{ @FXML private Button switchToBuyingBtn; @FXML private Button soledPropertiesBtn; @FXML private Button dashboardButton; @FXML private Button myPropertiesButton; @FXML private Button profileBtn; @FXML private Button sellPropertyBtn; @FXML private Button saveProfileBtn; @FXML private PasswordField passwordfeild; @FXML private TextField lastNameFeild; @FXML private TextField ageFeild; @FXML private TextField emailFeild; @FXML private TextField firstNameFeild; @FXML void dashboard(ActionEvent event) throws IOException { App.setRoot("SellerDashboard"); } @FXML void myProperty(ActionEvent event) throws IOException { App.setRoot("SellerListings"); } @FXML void profile(ActionEvent event) throws IOException { App.setRoot("SellerEditProfile"); } @FXML void sellProperty(ActionEvent event) throws IOException { App.setRoot("AddProperty"); } @FXML void soldProperties(ActionEvent event) throws IOException { App.setRoot("SoldProperties"); } @FXML void saveProfile(ActionEvent event) throws SQLException { LoginController controller = new LoginController(); int id = Integer.parseInt(controller.getId()); String firstName = firstNameFeild.getText().toString(); String lastName = lastNameFeild.getText().toString(); int age = Integer.parseInt(ageFeild.getText().toString()); String email = emailFeild.getText().toString(); String password = <PASSWORD>.getText().toString(); ConnectionClass connectionClass = new ConnectionClass(); Connection connection = connectionClass.getConnection(); String query = "update users set first_name=?, last_name=?, email=?, age=?, role=?,password=? where id=?"; String query1 = "update user_details set email=?, password=?, role=? where id=?"; PreparedStatement preparedStmt = connection.prepareStatement(query); PreparedStatement preparedStmt1 = connection.prepareStatement(query1); preparedStmt1.setString(1, email); preparedStmt1.setString(2, password); preparedStmt1.setString(3, "user"); preparedStmt1.setInt(4, id); preparedStmt.setString(1, firstName); preparedStmt.setString(2, lastName); preparedStmt.setString(3, email); preparedStmt.setInt(4, age); preparedStmt.setString(5, "user"); preparedStmt.setString(6, password); preparedStmt.setInt(7, id); preparedStmt.executeUpdate(); preparedStmt1.executeUpdate(); connection.close(); Alert a = new Alert(AlertType.NONE); a.setAlertType(AlertType.INFORMATION); // set content text a.setContentText("Profile Edited Successful!\n Your UserName is "+firstName+"_"+lastName+"\n Password is "+password); // show the dialog a.show(); } @FXML void switchToBuying(ActionEvent event) throws IOException { App.setRoot("UserDashboard"); } @Override public void initialize(URL arg0, ResourceBundle arg1) { LoginController controller = new LoginController(); User user = controller.getUser(); firstNameFeild.setText(user.getFirstName()); lastNameFeild.setText(user.getLastName()); ageFeild.setText(Integer.toString(user.getAge())); emailFeild.setText(user.getEmail()); passwordfeild.setText(user.getPassword()); } } <file_sep>/newproject 2/src/main/java/com/mycompany/newproject/Seller.java package com.mycompany.newproject; import java.util.List; public class Seller extends User{ private List<Inquiry> inquiry; private List<Property> propertyOnSale; public Seller() { super(); // TODO Auto-generated constructor stub } public Seller(List<Inquiry> inquiry, List<Property> propertyOnSale) { super(); this.inquiry = inquiry; this.propertyOnSale = propertyOnSale; } public List<Inquiry> getInquiry() { return inquiry; } public void setInquiry(List<Inquiry> inquiry) { this.inquiry = inquiry; } public List<Property> getPropertyOnSale() { return propertyOnSale; } public void setPropertyOnSale(List<Property> propertyOnSale) { this.propertyOnSale = propertyOnSale; } } <file_sep>/newproject 2/src/main/java/com/mycompany/newproject/Buyer.java package com.mycompany.newproject; import java.util.List; public class Buyer extends User { private List<Property> propertyBought; private List<Inquiry> inquiries; public Buyer() { super(); // TODO Auto-generated constructor stub } public Buyer(String firstName, String lastName, String email, int age, String role, String password,List<Property> propertyBought, List<Inquiry> inquiries) { super(firstName, lastName, email, age, role, password); this.propertyBought = propertyBought; this.inquiries = inquiries; } public List<Property> getPropertyBought() { return propertyBought; } public void setPropertyBought(List<Property> propertyBought) { this.propertyBought = propertyBought; } public List<Inquiry> getInquiries() { return inquiries; } public void setInquiries(List<Inquiry> inquiries) { this.inquiries = inquiries; } } <file_sep>/newproject 2/src/main/java/com/mycompany/newproject/PropertyTypeController.java package com.mycompany.newproject; import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.Pane; public class PropertyTypeController implements Initializable{ @FXML private Button addPropertyTypeBtn; @FXML private Button editPropertyTypeBtn; @FXML private Button deletePropertyType; @FXML private TableView<PropertyType> propertyTypeTable; @FXML private TableColumn<PropertyType, String> propertyTypeCol; @FXML private Pane addPropertyTypePane; @FXML private TextField eet_propertyType; @FXML private Button submitBtn; @FXML private Button clientsButton; @FXML private Button logoutButton; @FXML private Button ownerButton; @FXML private Button cityButton; @FXML private Button stateButton; @FXML private Button reviewsButton; @FXML private Button countryButton; @FXML private Button dashboardButton; @FXML private Button propertyButton; @FXML private Button propertyTypeButton; @FXML void addPropertyType(ActionEvent event) throws SQLException { addPropertyTypePane.setVisible(true); submitBtn.setOnAction(e->{ try { String name = eet_propertyType.getText().toString(); ConnectionClass connectionClass = new ConnectionClass(); Connection connection = connectionClass.getConnection(); String query = "insert into property_types (name)" + " values (?)"; PreparedStatement preparedStmt = connection.prepareStatement(query); preparedStmt.setString(1, name); preparedStmt.execute(); connection.close(); Alert a = new Alert(AlertType.NONE); a.setAlertType(AlertType.INFORMATION); // set content text a.setContentText("Property Type Added Successfully!"); // show the dialog a.show(); addPropertyTypePane.setVisible(false); populateTable(); eet_propertyType.setText(""); } catch (Exception e2) { e2.printStackTrace(); } }); } @FXML void deletePropertyType(ActionEvent event) throws SQLException { PropertyType propType = new PropertyType(); propType = propertyTypeTable.getSelectionModel().getSelectedItem(); String propertyType = propType.getType(); String query = "DELETE FROM property_types WHERE name = ?"; ConnectionClass connectionClass = new ConnectionClass(); Connection connection = connectionClass.getConnection(); PreparedStatement preparedStmt; try { preparedStmt = connection.prepareStatement(query); preparedStmt.setString(1, propertyType); preparedStmt.execute(); }catch (Exception e) { e.printStackTrace(); } Alert a = new Alert(AlertType.NONE); a.setAlertType(AlertType.INFORMATION); // set content text a.setContentText("Property Type Deleted Successfully!"); // show the dialog a.show(); populateTable(); } @FXML void editPropertyType(ActionEvent event) { addPropertyTypePane.setVisible(true); PropertyType propertyType = propertyTypeTable.getSelectionModel().getSelectedItem(); eet_propertyType.setText(propertyType.getType()); submitBtn.setOnAction(e->{ try { ConnectionClass connectionClass = new ConnectionClass(); Connection connection = connectionClass.getConnection(); String query = "update property_types set name = ? where name = ?"; PreparedStatement preparedStmt = connection.prepareStatement(query); preparedStmt.setString(1, eet_propertyType.getText().toString()); preparedStmt.setString(2, propertyType.getType()); // execute the java preparedstatement preparedStmt.executeUpdate(); connection.close(); Alert a = new Alert(AlertType.NONE); a.setAlertType(AlertType.INFORMATION); // set content text a.setContentText("Property Type Updated Successfully!"); // show the dialog a.show(); addPropertyTypePane.setVisible(false); populateTable(); eet_propertyType.setText(""); } catch (Exception e2) { e2.printStackTrace(); } }); } @FXML void city(ActionEvent event) throws IOException { App.setRoot("City"); } @FXML void clientList(ActionEvent event) throws IOException { App.setRoot("ClientList"); } @FXML void country(ActionEvent event) throws IOException { App.setRoot("Country"); } @FXML void dashboard(ActionEvent event) throws IOException { App.setRoot("AdminDashboard"); } @FXML void listProperties(ActionEvent event) throws IOException { App.setRoot("ListProperty"); } @FXML void logout(ActionEvent event) throws IOException { App.setRoot("Login"); } @FXML void ownerList(ActionEvent event) throws IOException { App.setRoot("OwnersList"); } @FXML void propertyType(ActionEvent event) throws IOException { App.setRoot("PropertyTypes"); } @FXML void profile(ActionEvent event) throws IOException { App.setRoot("AdminEditProfile"); } @FXML void state(ActionEvent event) throws IOException { App.setRoot("State"); } @Override public void initialize(URL location, ResourceBundle resources) { addPropertyTypePane.setVisible(false); try { populateTable(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void populateTable() throws SQLException{ ConnectionClass connectionClass = new ConnectionClass(); Connection connection = connectionClass.getConnection(); String query1 = "SELECT name from property_types"; PreparedStatement preparedStmt1; try { preparedStmt1 = connection.prepareStatement(query1); ResultSet resultSet = preparedStmt1.executeQuery(); ObservableList row = FXCollections.observableArrayList(); while (resultSet.next()) { for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) { row.add(resultSet.getString(i).toString()); System.out.println(row); } // data.add(row); } List<PropertyType> types = new ArrayList<PropertyType>(); for(int i =0 ; i<row.size();i++){ PropertyType type = new PropertyType(); type.setType(row.get(i).toString()); types.add(type); } ObservableList<PropertyType> propertyTypeObservable =FXCollections.observableArrayList(types); propertyTypeCol.setCellValueFactory(new PropertyValueFactory<PropertyType, String>("type")); propertyTypeTable.setItems(propertyTypeObservable); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } connection.close(); } } <file_sep>/newproject 2/src/main/java/com/mycompany/newproject/ViewPropertyController.java package com.mycompany.newproject; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.TextField; public class ViewPropertyController implements Initializable{ @FXML private Button dashboardButton; @FXML private Button propertyButton; @FXML private Button propertyTypeButton; @FXML private Button myPropertiesButton; @FXML private Button logoutButton; @FXML private Button ownerButton; @FXML private Button inquiryButton; @FXML private TextField propertyNameField; @FXML private TextField propertyAddressField; @FXML private TextField propertyPriceField; @FXML private TextField PropertyBedroomField; @FXML void dashboard(ActionEvent event) throws IOException { App.setRoot("UserDashboard"); } @FXML void inquiry(ActionEvent event) throws IOException { App.setRoot("UserInquiries"); } @FXML void listProperties(ActionEvent event) throws IOException { App.setRoot("UserPropertyList"); } @FXML void logout(ActionEvent event) throws IOException { App.setRoot("Login"); } @FXML void myProperty(ActionEvent event) throws IOException { App.setRoot("UserBoughtProperties"); } @FXML void ownerList(ActionEvent event) throws IOException { App.setRoot("UserPropertyList"); } @FXML void propertyType(ActionEvent event) throws IOException { App.setRoot("UserPropertyTypes"); } @Override public void initialize(URL arg0, ResourceBundle arg1) { UserPropertyListController userController = new UserPropertyListController(); viewProperty(userController.getViewProperty()); } public void viewProperty(Property property){ this.propertyNameField.setText(property.getPropertyName()); } } <file_sep>/newproject 2/src/main/java/com/mycompany/newproject/CityController.java package com.mycompany.newproject; import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.cell.PropertyValueFactory; public class CityController implements Initializable{ @FXML private Button deleteCityBtn; @FXML private TableView<Address> cityTable; @FXML private TableColumn<Address, String> countryCol; @FXML private TableColumn<Address, String> stateCol; @FXML private TableColumn<Address, String> cityCol; @FXML private Button addCityBtn; @FXML private TextField et_addCity; @FXML private ComboBox<String> countryBox; @FXML private ComboBox<String> stateBox; @FXML private Button clientsButton; @FXML private Button logoutButton; @FXML private Button ownerButton; @FXML private Button cityButton; @FXML private Button stateButton; @FXML private Button profileBtn; @FXML private Button countryButton; @FXML private Button dashboardButton; @FXML private Button propertyButton; @FXML private Button propertyTypeButton; @FXML void city(ActionEvent event) throws IOException { App.setRoot("City"); } @FXML void clientList(ActionEvent event) throws IOException { App.setRoot("ClientList"); } @FXML void country(ActionEvent event) throws IOException { App.setRoot("Country"); } @FXML void dashboard(ActionEvent event) throws IOException { App.setRoot("AdminDashboard"); } @FXML void listProperties(ActionEvent event) throws IOException { App.setRoot("ListProperty"); } @FXML void logout(ActionEvent event) throws IOException { App.setRoot("Login"); } @FXML void ownerList(ActionEvent event) throws IOException { App.setRoot("OwnersList"); } @FXML void propertyType(ActionEvent event) throws IOException { App.setRoot("PropertyTypes"); } @FXML void profile(ActionEvent event) throws IOException { App.setRoot("AdminEditProfile"); } @FXML void state(ActionEvent event) throws IOException { App.setRoot("State"); } @FXML void addCity(ActionEvent event) { String city = et_addCity.getText().toString(); String state = stateBox.getSelectionModel().getSelectedItem().toString(); String country = countryBox.getSelectionModel().getSelectedItem().toString(); String state_id; ConnectionClass connectionClass = new ConnectionClass(); Connection connection = connectionClass.getConnection(); PreparedStatement preparedStmt = null; String query = "select id from states where name = ?"; try { preparedStmt = connection.prepareStatement(query); preparedStmt.setString(1,state); ResultSet resultSet = preparedStmt.executeQuery(); ObservableList row = FXCollections.observableArrayList(); while (resultSet.next()) { for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) { row.add(resultSet.getString(i).toString()); System.out.println(row); } // data.add(row); } state_id = row.get(0).toString(); String query1 = "insert into cities (state_id, name)" + " values (?, ?)"; PreparedStatement preparedStatement1; preparedStatement1 = connection.prepareStatement(query1); preparedStatement1.setString(1,state_id); preparedStatement1.setString(2, city); preparedStatement1.execute(); connection.close(); Alert a = new Alert(AlertType.NONE); a.setAlertType(AlertType.INFORMATION); // set content text a.setContentText("City Added Successfully!"); // show the dialog a.show(); populateTable(); et_addCity.setText(""); countryBox.setAccessibleText("Select Country"); stateBox.setAccessibleText("Select State"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @FXML void deleteCity(ActionEvent event) throws SQLException { Address state = new Address(); state = cityTable.getSelectionModel().getSelectedItem(); String cityName = state.getCity(); String query = "DELETE FROM cities WHERE name = ?"; ConnectionClass connectionClass = new ConnectionClass(); Connection connection = connectionClass.getConnection(); PreparedStatement preparedStmt; try { preparedStmt = connection.prepareStatement(query); preparedStmt.setString(1, cityName); preparedStmt.execute(); }catch (Exception e) { e.printStackTrace(); } Alert a = new Alert(AlertType.NONE); a.setAlertType(AlertType.INFORMATION); // set content text a.setContentText("City Deleted Successfully!"); // show the dialog a.show(); populateTable(); } @Override public void initialize(URL location, ResourceBundle resources) { try { populateTable(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } ConnectionClass connectionClass = new ConnectionClass(); Connection connection = connectionClass.getConnection(); String query = "select name from countries"; PreparedStatement preparedStmt; try { preparedStmt = connection.prepareStatement(query); ResultSet resultSet = preparedStmt.executeQuery(); ObservableList row = FXCollections.observableArrayList(); while (resultSet.next()) { for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) { row.add(resultSet.getString(i).toString()); // System.out.println(row); } // data.add(row); } countryBox.setItems(row); connection.close(); stateBox.setOnMouseClicked(e->{ try { ConnectionClass connectionClass1 = new ConnectionClass(); Connection connection1 = connectionClass1.getConnection(); String countryName = countryBox.getSelectionModel().getSelectedItem().toString(); PreparedStatement preparedStmt2; String query2 = "select id from countries where name = ?"; String country_id; preparedStmt2 = connection1.prepareStatement(query2); preparedStmt2.setString(1,countryName); ResultSet resultSet2 = preparedStmt2.executeQuery(); ObservableList row2 = FXCollections.observableArrayList(); while (resultSet2.next()) { for (int i = 1; i <= resultSet2.getMetaData().getColumnCount(); i++) { row2.add(resultSet2.getString(i).toString()); System.out.println(row2); } // data.add(row); } country_id = row2.get(0).toString(); connection1.close(); ConnectionClass connectionClass2 = new ConnectionClass(); Connection connection2 = connectionClass2.getConnection(); String query1 = "SELECT name from states where country_id=?"; PreparedStatement preparedStatement; preparedStatement = connection2.prepareStatement(query1); preparedStatement.setString(1,country_id); ResultSet rs = preparedStatement.executeQuery(); ObservableList row1 = FXCollections.observableArrayList(); while (rs.next()) { for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { row1.add(rs.getString(i).toString()); // System.out.println(row1); } // data.add(row); } connection2.close(); stateBox.setItems(row1); } catch (Exception e2) { // TODO: handle exception } }); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void populateTable() throws SQLException{ ConnectionClass connectionClass = new ConnectionClass(); Connection connection = connectionClass.getConnection(); String query1 = "SELECT cities.name,states.name,countries.name FROM cities INNER JOIN states ON cities.state_id = states.id INNER JOIN countries ON states.country_id = countries.id;"; PreparedStatement preparedStmt1; try { preparedStmt1 = connection.prepareStatement(query1); ResultSet resultSet = preparedStmt1.executeQuery(); ObservableList row = FXCollections.observableArrayList(); while (resultSet.next()) { for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) { row.add(resultSet.getString(i).toString()); System.out.println(row); } // data.add(row); } List<Address> states = new ArrayList<Address>(); for(int i =0 ; i<row.size();i++){ Address state = new Address(); state.setCity(row.get(i).toString()); i++; state.setState(row.get(i).toString()); i++; state.setCountry(row.get(i).toString()); states.add(state); } ObservableList<Address> stateObservable =FXCollections.observableArrayList(states);; countryCol.setCellValueFactory(new PropertyValueFactory<Address, String>("country")); cityCol.setCellValueFactory(new PropertyValueFactory<Address, String>("city")); stateCol.setCellValueFactory(new PropertyValueFactory<Address, String>("state")); cityTable.setItems(stateObservable); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } connection.close(); } } <file_sep>/newproject 2/src/main/java/com/mycompany/newproject/UserPropertyListController.java package com.mycompany.newproject; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.sql.Blob; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import javax.imageio.ImageIO; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.embed.swing.SwingFXUtils; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.DatePicker; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.ButtonType; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.GridPane; import javafx.scene.text.Text; import javafx.stage.Stage; public class UserPropertyListController implements Initializable{ @FXML private Button by_rentButton; @FXML private Button viewButton; @FXML private Button switchToSelling; @FXML private TableView<Property> property_table; @FXML private TableColumn<Property, String> nameCol; @FXML private TableColumn<Property, String> typeCol; @FXML private TableColumn<Property, String> addressCol; @FXML private TableColumn<Property, String> bedsCol; @FXML private TableColumn<Property, String> sq_feetCol; @FXML private TableColumn<Property, String> status; @FXML private TableColumn<Property, String> price; @FXML private Button logoutButton1; @FXML private Button inquiryButton1; @FXML private Button ownerButton1; @FXML private Button myPropertiesButton1; @FXML private Button propertyTypeButton1; @FXML private Button propertyButton1; @FXML private Button dashboardButton1; static List<Property> propertyList = new ArrayList<Property>(); private static Property property = new Property(); @FXML void dashboard(ActionEvent event) throws IOException { App.setRoot("UserDashboard"); } @FXML void inquiry(ActionEvent event) throws IOException { App.setRoot("UserInquiries"); } @FXML void listProperties(ActionEvent event) throws IOException { App.setRoot("UserPropertyList"); } @FXML void logout(ActionEvent event) throws IOException { App.setRoot("Login"); } @FXML void myProperty(ActionEvent event) throws IOException { App.setRoot("UserBoughtProperties"); } @FXML void ownerList(ActionEvent event) throws IOException { App.setRoot("UserPropertyList"); } @FXML void propertyType(ActionEvent event) throws IOException { App.setRoot("UserPropertyTypes"); } @FXML void View(ActionEvent event) throws IOException { this.property = this.property_table.getSelectionModel().getSelectedItem(); System.out.println(property.getPropertyName()); App.setRoot("ViewProperty"); } @FXML void switchToSelling(ActionEvent event) throws IOException { App.setRoot("SellerDashboard"); } @FXML void buyRent(ActionEvent event) throws IOException { LoginController controller = new LoginController(); String id = controller.getId(); ImageView imageView = new ImageView(); String propertyId = null; Property property=property_table.getSelectionModel().getSelectedItem(); ConnectionClass connectionClass = new ConnectionClass(); Connection connection = connectionClass.getConnection(); String query1 = "SELECT id,city,state,country,address,name,type,status,price,sq_feet,no_of_beds,year_built,description,owner_id from properties where name = ?"; PreparedStatement preparedStmt1; try { preparedStmt1 = connection.prepareStatement(query1); preparedStmt1.setString(1, property.getPropertyName()); ResultSet resultSet = preparedStmt1.executeQuery(); ObservableList row = FXCollections.observableArrayList(); while (resultSet.next()) { for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) { row.add(resultSet.getString(i).toString()); System.out.println(row); } // data.add(row); } propertyId= row.get(0).toString(); String city =row.get(1).toString(); String state=row.get(2).toString(); String country=row.get(3).toString(); property.setLocation(row.get(4).toString()+","+city+","+state+","+country); property.setPropertyName(row.get(5).toString()); property.setType(row.get(6).toString()); property.setStatus(row.get(7).toString()); property.setPrice(row.get(8).toString()); property.setSquareFeetArea(row.get(9).toString()); property.setNoOfBeds(row.get(10).toString()); property.setDescription(row.get(12).toString()); property.setOwner(row.get(13).toString()); connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try{ ConnectionClass connectionClass1 = new ConnectionClass(); Connection connection1 = connectionClass1.getConnection(); File file=new File("User\\paragkhodke\\NetBeansProject\\newproject2\\src\\main\\resources\\com\\mycompany\\newproject\\images\\newimage.jpg"); FileOutputStream fos=new FileOutputStream(file); byte b[]; Blob blob; PreparedStatement ps=connection1.prepareStatement("select picture from properties where id=?"); ps.setString(1, propertyId); ResultSet rs=ps.executeQuery(); while(rs.next()){ blob=rs.getBlob("picture"); b=blob.getBytes(1,(int)blob.length()); fos.write(b); } ps.close(); fos.close(); connection1.close(); }catch(Exception e){ e.printStackTrace(); } File file = new File("User\\paragkhodke\\NetBeansProject\\newproject2\\src\\main\\resources\\com\\mycompany\\newproject\\images\\newimage.jpg"); BufferedImage bufferedImage; try { bufferedImage = ImageIO.read(file); Image image = SwingFXUtils.toFXImage(bufferedImage, null); imageView.setImage(image); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Text text1 = new Text("Property Name :"); Text text2 = new Text("Property Type :"); Text text3 = new Text("Property Address :"); Text text4 = new Text("Price :"); //adding label Text text5 = new Text("Property Area"); TextField textField6 = new TextField(); textField6.setText(property.getSquareFeetArea()); //creating the text field for the first name TextField textField1 = new TextField(); textField1.setText(property.getPropertyName()); textField1.setEditable(false); //creating the text field for the last name TextField textField2 = new TextField(); textField2.setText(property.getType()); textField2.setEditable(false); //creating the text field for the address TextField textField3 = new TextField(); textField3.setText(property.getLocation()); textField3.setEditable(false); //creating the text field for the salary TextField textField5 = new TextField(); textField5.setText(property.getPrice()); textField5.setEditable(false); //Creating Button Button button1 = new Button("Buy"); Button button2 = new Button("Cancel"); imageView.setFitHeight(300); imageView.setFitWidth(100); //Creating a Grid Pane GridPane gridPane = new GridPane(); //Arranging all the nodes in the grid gridPane.add(imageView, 1, 0); gridPane.add(text1, 0, 2); gridPane.add(textField1, 1, 2); gridPane.add(text2, 0, 3); gridPane.add(textField2, 1, 3); gridPane.add(text3, 0, 4); gridPane.add(textField3, 1, 4); gridPane.add(text4, 0, 5); gridPane.add(textField5, 1, 5); //add the item to be added in the grid pane gridPane.add(text5,0,6); gridPane.add(textField6,1,6); gridPane.add(button1,2,7); gridPane.add(button2, 3, 7); //first value is column second is row //setting the horizontal and vertical gap between all nodes gridPane.setHgap(10); gridPane.setVgap(10); gridPane.setMaxHeight(500); gridPane.setMaxWidth(300); gridPane.setMaxSize(500,300); //setting the padding gridPane.setPadding(new Insets(10, 10, 10, 10)); //setting the gid alignment to center gridPane.setAlignment(Pos.TOP_CENTER); //making a new scene and passing the gid pane to it Scene secondScene = new Scene(gridPane, 800, 600); // New window (Stage) gridPane.setStyle("-fx-background-color: white;"); Stage newWindow = new Stage(); newWindow.setTitle("Buy Property"); newWindow.setScene(secondScene); newWindow.setMaxHeight(800); newWindow.setMaxWidth(600); newWindow.show(); button1.setOnAction(e->{ ConnectionClass connectionClassX = new ConnectionClass(); Connection connectionX = connectionClassX.getConnection(); String query1X = "update properties set buyer_id=? ,status=? where name=?"; PreparedStatement preparedStmt1X; try { preparedStmt1X = connectionX.prepareStatement(query1X); preparedStmt1X.setString(1, id); preparedStmt1X.setString(2, "sold"); preparedStmt1X.setString(3, property.getPropertyName()); preparedStmt1X.executeUpdate(); Alert a1 = new Alert(null); a1.setAlertType(AlertType.CONFIRMATION); a1.setContentText("are you sure you want to buy/rent this property"); a1.show(); newWindow.close(); //Alert a = new Alert(null); // a.setAlertType(AlertType.INFORMATION); // a.setContentText("Property Bought/Rented Successfully !"); // a.show(); }catch (Exception e1) { e1.printStackTrace(); } }); button2.setOnAction(e->{ newWindow.close(); }); } @Override public void initialize(URL arg0, ResourceBundle arg1) { LoginController controller = new LoginController(); String id = controller.getId(); ConnectionClass connectionClass = new ConnectionClass(); Connection connection = connectionClass.getConnection(); String query1 = "SELECT city,state,country,address,name,type,status,price,sq_feet,no_of_beds from properties where owner_id !=? and status!= ?"; PreparedStatement preparedStmt1; try { preparedStmt1 = connection.prepareStatement(query1); preparedStmt1.setString(1, id); preparedStmt1.setString(2, "sold"); ResultSet resultSet = preparedStmt1.executeQuery(); ObservableList row = FXCollections.observableArrayList(); while (resultSet.next()) { for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) { row.add(resultSet.getString(i).toString()); System.out.println(row); } // data.add(row); } List<Property> properties = new ArrayList<Property>(); for(int i =0 ; i<row.size();i++){ Property property = new Property(); String city =row.get(i).toString(); i++; String state=row.get(i).toString(); i++; String country=row.get(i).toString(); i++; property.setLocation(row.get(i).toString()+","+city+","+state+","+country); i++; property.setPropertyName(row.get(i).toString()); i++; property.setType(row.get(i).toString()); i++; property.setStatus(row.get(i).toString()); i++; property.setPrice(row.get(i).toString()); i++; property.setSquareFeetArea(row.get(i).toString()); i++; property.setNoOfBeds(row.get(i).toString()); properties.add(property); } ObservableList<Property> stateObservable =FXCollections.observableArrayList(properties); nameCol.setCellValueFactory(new PropertyValueFactory<Property, String>("propertyName")); addressCol.setCellValueFactory(new PropertyValueFactory<Property, String>("location")); typeCol.setCellValueFactory(new PropertyValueFactory<Property, String>("type")); sq_feetCol.setCellValueFactory(new PropertyValueFactory<Property, String>("squareFeetArea")); status.setCellValueFactory(new PropertyValueFactory<Property, String>("status")); price.setCellValueFactory(new PropertyValueFactory<Property, String>("price")); bedsCol.setCellValueFactory(new PropertyValueFactory<Property, String>("noOfBeds")); property_table.setItems(stateObservable); connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void setProperty(Property property){ this.property = property; } public Property getViewProperty(){ return this.property; } } <file_sep>/newproject 2/src/main/java/com/mycompany/newproject/Property.java package com.mycompany.newproject; import java.security.acl.Owner; import java.util.List; public class Property { private String propertyName; private String location; private String owner; private String status; private String description; private String noOfBeds; private String type; private String squareFeetArea; private String price; private List<String> amenities; public Property() { super(); // TODO Auto-generated constructor stub } public Property(String propertyName, String location, String owner, String status, String description, String noOfBeds, String type, String squareFeetArea, String price, List<String> amenities) { super(); this.propertyName = propertyName; this.location = location; this.owner=owner; this.status = status; this.description = description; this.noOfBeds = noOfBeds; this.type = type; this.squareFeetArea = squareFeetArea; this.price = price; this.amenities = amenities; } public String getPropertyName() { return propertyName; } public void setPropertyName(String propertyName) { this.propertyName = propertyName; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getNoOfBeds() { return noOfBeds; } public void setNoOfBeds(String noOfBeds) { this.noOfBeds = noOfBeds; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getSquareFeetArea() { return squareFeetArea; } public void setSquareFeetArea(String squareFeetArea) { this.squareFeetArea = squareFeetArea; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public List<String> getAmenities() { return amenities; } public void setAmenities(List<String> amenities) { this.amenities = amenities; } } <file_sep>/newproject 2/src/main/java/com/mycompany/newproject/ClientListController.java package com.mycompany.newproject; import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; public class ClientListController implements Initializable{ @FXML private TableView<User> clientTable; @FXML private TableColumn<User, String> firstNameCol; @FXML private TableColumn<User, String> lastNameCol; @FXML private TableColumn<User, String> ageCol; @FXML private TableColumn<User, String> emailCol; @FXML private Button sendInquiryBtn; @FXML private Button clientsButton; @FXML private Button logoutButton; @FXML private Button ownerButton; @FXML private Button cityButton; @FXML private Button stateButton; @FXML private Button profileBtn; @FXML private Button countryButton; @FXML private Button dashboardButton; @FXML private Button propertyButton; @FXML private Button propertyTypeButton; @FXML void city(ActionEvent event) throws IOException { App.setRoot("City"); } @FXML void clientList(ActionEvent event) throws IOException { App.setRoot("ClientList"); } @FXML void country(ActionEvent event) throws IOException { App.setRoot("Country"); } @FXML void dashboard(ActionEvent event) throws IOException { App.setRoot("AdminDashboard"); } @FXML void listProperties(ActionEvent event) throws IOException { App.setRoot("ListProperty"); } @FXML void logout(ActionEvent event) throws IOException { App.setRoot("Login"); } @FXML void ownerList(ActionEvent event) throws IOException { App.setRoot("OwnersList"); } @FXML void propertyType(ActionEvent event) throws IOException { App.setRoot("PropertyTypes"); } @FXML void profile(ActionEvent event) throws IOException { App.setRoot("AdminEditProfile"); } @FXML void state(ActionEvent event) throws IOException { App.setRoot("State"); } @FXML void sendInquiry(ActionEvent event) { } @Override public void initialize(URL arg0, ResourceBundle arg1) { List<User> userList = new ArrayList<User>(); String role="user"; String query1 = "select * from users where role=?"; ConnectionClass connectionClass1 = new ConnectionClass(); Connection connection1 = connectionClass1.getConnection(); PreparedStatement preparedStmt1; try { preparedStmt1 = connection1.prepareStatement(query1); preparedStmt1.setString(1, role); ResultSet resultSet1 = preparedStmt1.executeQuery(); ObservableList row = FXCollections.observableArrayList(); while (resultSet1.next()) { for (int i = 1; i <= resultSet1.getMetaData().getColumnCount(); i++) { row.add(resultSet1.getString(i).toString()); System.out.println(row); } } for(int i =1 ; i<=row.size();i++){ User user = new User(); user.setFirstName(row.get(i).toString()); i++; user.setLastName(row.get(i).toString()); i++; user.setEmail(row.get(i).toString()); i++; user.setAge(Integer.parseInt(row.get(i).toString())); i++; user.setRole(row.get(i).toString()); i++; user.setPassword(row.get(i).toString()); i++; userList.add(user); } } catch (Exception e) { e.printStackTrace(); } firstNameCol.setCellValueFactory(new PropertyValueFactory<User, String>("firstName")); lastNameCol.setCellValueFactory(new PropertyValueFactory<User, String>("lastName")); ageCol.setCellValueFactory(new PropertyValueFactory<User, String>("age")); emailCol.setCellValueFactory(new PropertyValueFactory<User, String>("email")); ObservableList<User> userObservableList = FXCollections.observableArrayList(userList); this.clientTable.setItems(userObservableList); } } <file_sep>/newproject 2/src/main/java/com/mycompany/newproject/SoldPropertiesController.java package com.mycompany.newproject; import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; public class SoldPropertiesController implements Initializable{ @FXML private Button switchToBuyingBtn; @FXML private Button soledPropertiesBtn; @FXML private Button dashboardButton; @FXML private Button myPropertiesButton; @FXML private Button profileBtn; @FXML private Button sellPropertyBtn; @FXML private Button viewButton; @FXML private TableView<Property> property_table; @FXML private TableColumn<Property, String> nameCol; @FXML private TableColumn<Property, String> typeCol; @FXML private TableColumn<Property, String> addressCol; @FXML private TableColumn<Property,String> bedsCol; @FXML private TableColumn<Property,String> sq_feetCol; @FXML private TableColumn<Property,String> status; @FXML private TableColumn<Property, String> price; static List<Property> propertyList = new ArrayList<Property>(); private static Property property = new Property(); @FXML void View(ActionEvent event) throws IOException { this.property = this.property_table.getSelectionModel().getSelectedItem(); SellerListingsController controller = new SellerListingsController(); controller.setProperty(this.property); System.out.println(property.getPropertyName()); App.setRoot("ViewSellerProperty"); } @FXML void dashboard(ActionEvent event) throws IOException { App.setRoot("SellerDashboard"); } @FXML void myProperty(ActionEvent event) throws IOException { App.setRoot("SellerListings"); } @FXML void profile(ActionEvent event) throws IOException { App.setRoot("SellerEditProfile"); } @FXML void sellProperty(ActionEvent event) throws IOException { App.setRoot("AddProperty"); } @FXML void soldProperties(ActionEvent event) throws IOException { App.setRoot("SoldProperties"); } @FXML void switchToBuying(ActionEvent event) throws IOException { App.setRoot("UserDashboard"); } @Override public void initialize(URL arg0, ResourceBundle arg1) { LoginController controller = new LoginController(); String id = controller.getId(); ConnectionClass connectionClass = new ConnectionClass(); Connection connection = connectionClass.getConnection(); String query1 = "SELECT city,state,country,address,name,type,status,price,sq_feet,no_of_beds from properties where owner_id =? and status=?"; PreparedStatement preparedStmt1; try { preparedStmt1 = connection.prepareStatement(query1); preparedStmt1.setString(1, id); preparedStmt1.setString(2, "sold"); ResultSet resultSet = preparedStmt1.executeQuery(); ObservableList row = FXCollections.observableArrayList(); while (resultSet.next()) { for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) { row.add(resultSet.getString(i).toString()); System.out.println(row); } // data.add(row); } List<Property> properties = new ArrayList<Property>(); for(int i =0 ; i<row.size();i++){ Property property = new Property(); String city =row.get(i).toString(); i++; String state=row.get(i).toString(); i++; String country=row.get(i).toString(); i++; property.setLocation(row.get(i).toString()+","+city+","+state+","+country); i++; property.setPropertyName(row.get(i).toString()); i++; property.setType(row.get(i).toString()); i++; property.setStatus(row.get(i).toString()); i++; property.setPrice(row.get(i).toString()); i++; property.setSquareFeetArea(row.get(i).toString()); i++; property.setNoOfBeds(row.get(i).toString()); properties.add(property); } ObservableList<Property> stateObservable =FXCollections.observableArrayList(properties); nameCol.setCellValueFactory(new PropertyValueFactory<Property, String>("propertyName")); addressCol.setCellValueFactory(new PropertyValueFactory<Property, String>("location")); typeCol.setCellValueFactory(new PropertyValueFactory<Property, String>("type")); sq_feetCol.setCellValueFactory(new PropertyValueFactory<Property, String>("squareFeetArea")); status.setCellValueFactory(new PropertyValueFactory<Property, String>("status")); price.setCellValueFactory(new PropertyValueFactory<Property, String>("price")); bedsCol.setCellValueFactory(new PropertyValueFactory<Property, String>("noOfBeds")); property_table.setItems(stateObservable); connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public Property getViewProperty(){ return this.property; } } <file_sep>/newproject 2/src/main/java/com/mycompany/newproject/OwnerLoginController.java package com.mycompany.newproject; import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import java.util.Timer; import java.util.TimerTask; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; public class OwnerLoginController implements Initializable{ @FXML private Button loginButton; @FXML private TextField usernamefeild; @FXML private PasswordField passwordfeild; @FXML private Button signupBtn; @FXML private ImageView slideShow; public int count = 0; private static User user = new User(); private static String user_id; @FXML void login(ActionEvent event) throws IOException { String userName = usernamefeild.getText().toString(); String password = <PASSWORD>feild.getText().toString(); String query1 = "select * from users where email = ? and password = ?"; ConnectionClass connectionClass1 = new ConnectionClass(); Connection connection1 = connectionClass1.getConnection(); PreparedStatement preparedStmt1; try { preparedStmt1 = connection1.prepareStatement(query1); preparedStmt1.setString(1, userName); preparedStmt1.setString(2, password); ResultSet resultSet1 = preparedStmt1.executeQuery(); ObservableList row = FXCollections.observableArrayList(); while (resultSet1.next()) { for (int i = 1; i <= resultSet1.getMetaData().getColumnCount(); i++) { row.add(resultSet1.getString(i).toString()); System.out.println(row); } } for(int i =0 ; i<row.size();i++){ user_id = row.get(i).toString(); i++; user.setFirstName(row.get(i).toString()); i++; user.setLastName(row.get(i).toString()); i++; user.setEmail(row.get(i).toString()); i++; user.setAge(Integer.parseInt(row.get(i).toString())); i++; user.setRole(row.get(i).toString()); i++; user.setPassword(row.get(i).toString()); } } catch (Exception e) { e.printStackTrace(); } String role = "seller"; ConnectionClass connectionClass = new ConnectionClass(); Connection connection = connectionClass.getConnection(); String query = "select * from user_details where email = ? and password = ? and role=?"; PreparedStatement preparedStmt; try { preparedStmt = connection.prepareStatement(query); preparedStmt.setString(1, userName); preparedStmt.setString(2, password); preparedStmt.setString(3, role); // Alert a = new Alert(AlertType.NONE); // execute the preparedstatement ResultSet resultSet = preparedStmt.executeQuery(); if(!resultSet.next()){ //App.setRoot("Login"); usernamefeild.setText(""); passwordfeild.setText(""); // set alert type /// a.setAlertType(AlertType.ERROR); // set content text /// a.setContentText("Wrong UserName or Password!\n Please Try Again"); // show the dialog /// a.show(); }else{ try { Thread.sleep(1000); } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } System.out.println("Success"); App.setRoot("SellerDashboard"); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } @FXML void signUp(ActionEvent event) throws IOException { App.setRoot("SellerSignUp"); } @Override public void initialize(URL arg0, ResourceBundle arg1) { usernamefeild.setStyle("-fx-text-fill: white; -fx-font-size: 18px; -fx-background-color:#000000;-fx-border-color: #6A4E66"); passwordfeild.setStyle("-fx-text-fill: white; -fx-font-size: 18px; -fx-background-color:#000000;-fx-border-color: #6A4E66"); Image image = new Image("com/mycompany/newproject/images/background9.jpg"); Image image1 = new Image("com/mycompany/newproject/images/background12.jpg"); Image image2= new Image("com/mycompany/newproject/images/background23.jpg"); Image image3 = new Image("com/mycompany/newproject/images/background24.jpg"); Image image4 = new Image("com/mycompany/newproject/images/background25.jpg"); List<Image> imageArrayList = new ArrayList<Image>(); imageArrayList.add(image1); imageArrayList.add(image); imageArrayList.add(image2); imageArrayList.add(image3); imageArrayList.add(image4); // then in your method long delay = 2000; //update once per 2 seconds. new Timer().schedule(new TimerTask() { @Override public void run() { slideShow.setImage(imageArrayList.get(count++)); if (count >= imageArrayList.size()) { count = 0; } } }, 0, delay); } public User getUser(){ return this.user; } public String getId(){ return this.user_id; } }
f444d0085eb90381d7eae3745761e3ad51d19ad5
[ "Markdown", "Java" ]
17
Java
paragkhodke72/RealEstateManagementSystem
ebb0310069cec2441c0ae294ac03b79d9037027a
16f59f5f250b0011572f3599d4459d6b3e980125
refs/heads/master
<file_sep>#include <iostream> class LinkedListNode{ public: LinkedListNode(); LinkedListNode(int x); ~LinkedListNode(); int value; LinkedListNode * next; }; LinkedListNode::LinkedListNode(){ value = -1; next = NULL; } LinkedListNode::LinkedListNode(int x){ value = x; next = NULL; } LinkedListNode::~LinkedListNode(){ } class LinkedList{ LinkedListNode * head; public: LinkedList(); ~LinkedList(); void add(int x); void display(); void reverse(); }; LinkedList::LinkedList(){ head = NULL; } LinkedList::~LinkedList(){ } void LinkedList::add(int x){ LinkedListNode *t = head; if (head==NULL) head = new LinkedListNode(x); else{ while(t->next != NULL) t = t->next; t->next = new LinkedListNode(x); } } void LinkedList::display(){ LinkedListNode *t = head; while(t != NULL){ std::cout << t->value << " - " ; t=t->next; } std::cout << std::endl; } void LinkedList::reverse(){ if(head != NULL){ LinkedListNode *a = head; LinkedListNode *b = NULL; LinkedListNode *c = NULL; while(a->next != NULL){ b = a->next; a->next = c; c = a; a = b; } a->next = c; head = a; } } int main(){ LinkedList list; list.add(4); list.add(5); list.add(6); list.display(); list.reverse(); list.display(); }
d238cfc36c49e27834a4efb7b84292d879898bf7
[ "C++" ]
1
C++
csqzhang/C-DataStructure-Solution
dded46ac40574408062ca954e3e631ee831199bb
4f320451e599b253f55971d00713c80b4996c9b4
refs/heads/master
<repo_name>gem007bd/grades<file_sep>/Grades/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Grades { class Program { static void Main ( string[] args ) { GradeBook book = new GradeBook(); book.AddGrade(90); book.AddGrade(89.9f); book.AddGrade(150); GradeStatics states = book.ComputeStateics(); Console.WriteLine(states.AverageGrade); Console.WriteLine(states.HeighestGrade); Console.WriteLine(states.LowestGrade); } } } <file_sep>/Grades/GradeBook.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Grades { class GradeBook { public GradeBook () { grades = new List<float>(); } public void AddGrade (float grade) { grades.Add(grade); } public GradeStatics ComputeStateics () { GradeStatics states = new GradeStatics(); float sum = 0; foreach(float grade in grades){ states.HeighestGrade = Math.Max( grade, states.HeighestGrade); states.LowestGrade = Math.Min(grade, states.LowestGrade); sum += grade; } states.AverageGrade = sum / grades.Count; return states; } private List<float> grades; } }
e18caf286bdeb21924aa7ae21f32d6b0a286023e
[ "C#" ]
2
C#
gem007bd/grades
af13d0d758083a09e12730f2193a117a2d65247d
d5e345ee12cf51fef5dd2d95fd38c27edcd61dec
refs/heads/main
<file_sep>package usuario.fisica.voluntario; import java.util.List; import cidade.Cidade; import endereco.Endereco; import livro.Livro; import usuario.Tipo; import usuario.fisica.Perfil; import usuario.fisica.PessoaFisica; public class Voluntario extends PessoaFisica { private double pontuacao; private List<Livro> livros; public Voluntario(String email, String nome, String cpf, String rg, String telefone) throws Exception { super(email, nome, cpf, rg, telefone); } public Voluntario(String email, String senha, Cidade cidade, Endereco endereco, Tipo tipo, String nome, String cpf, String rg, String telefone, List<Perfil> perfis, double pontuacao) throws Exception { super(email, senha, cidade, endereco, tipo, nome, cpf, rg, telefone, perfis); this.pontuacao = pontuacao; } public Voluntario(String email, double pontuacao) { this.email = email; this.pontuacao = pontuacao; } public void print() { super.print(); System.out.println("Pontuação: " + pontuacao); if (livros != null && livros.size() > 0) { System.out.println("Livros: "); for (Livro livro : livros) { livro.print(); } } } public double getPontuacao() { return pontuacao; } public void setPontuacao(double pontuacao) { this.pontuacao = pontuacao; } public List<Livro> getLivros() { return livros; } public void setLivros(List<Livro> livros) { this.livros = livros; } } <file_sep>create table cidade ( id int not null, nome_cidade varchar2(40) not null, uf_cidade char(2) not null, constraint pk_cidade primary key (id), constraint sk_cidade unique (nome_cidade, uf_cidade) ); create table endereco ( id int not null, cep varchar2(10), numero number, rua varchar2(60), bairro varchar2(60), complemento varchar2(80), constraint pk_endereco primary key (id) ); create table usuario ( email varchar2(100) not null, senha varchar2(20) not null, cidade_id int not null, endereco_id int, tipo_usuario varchar2(15), constraint pk_usuario primary key (email), constraint fk1_usuario foreign key (cidade_id) references cidade (id), constraint fk2_usuario foreign key (endereco_id) references endereco(id), constraint ck_tipo_usuario check (tipo_usuario = 'PESSOA_FISICA' or tipo_usuario = 'PESSOA_JURIDICA') ); create table pessoa_fisica ( email_usuario_pf varchar2(100) not null, nome_usuario_pf varchar2(50) not null, cpf_usuario_pf varchar2(15) not null, rg_usuario_pf varchar2(9), telefone_usuario_pf varchar2(15), constraint pk_pessoa_fisica primary key (email_usuario_pf), constraint sk_pessoa_fisica unique (cpf_usuario_pf), constraint fk_pessoa_fisica foreign key (email_usuario_pf) references usuario (email) on delete cascade ); create table perfis ( email_usuario_pf varchar2(100) not null, perfil varchar2(15) not null, constraint pk_perfis primary key (email_usuario_pf, perfil), constraint fk_perfis foreign key (email_usuario_pf) references pessoa_fisica (email_usuario_pf) on delete cascade, constraint ck_perfis check (perfil = 'DOADOR' or perfil = 'DONATARIO' or perfil = 'VOLUNTARIO') ); create table pessoa_juridica ( email_usuario_pj varchar2(100) not null, razao_social varchar2(50) not null, nome_fantasia varchar2(50) not null, cnpj_usuario_pj varchar2(18) not null, inscricao_estadual varchar2(20), constraint pk_pessoa_juridica primary key (email_usuario_pj), constraint sk_pessoa_juridica unique (cnpj_usuario_pj), constraint fk_pessoa_juridica foreign key (email_usuario_pj) references usuario (email) on delete cascade ); create table administrador ( email_adm varchar2(100) not null, senha_adm varchar2(20) not null, nome_adm varchar2(50) not null, data_registro date not null, constraint pk_administrador primary key (email_adm) ); create table livro ( codigo_barras number not null, autor varchar2(50) not null, titulo varchar2(50) not null, isbn number not null, edicao varchar2(30) not null, condicao number not null, origem varchar2(15) not null, constraint pk_livro primary key (codigo_barras), constraint ck_livro check (origem = 'DOADOR' or origem = 'VOLUNTARIO' or origem = 'PESSOA_JURIDICA' or origem = 'ADMINISTRADOR'), constraint ck_condicao_livro check (condicao in (1, 2, 3, 4)) ); create table bibliotecario ( cib number not null, senha_bibliotecario varchar2(30) not null, nome_bibliotecario varchar2(50) not null, cidade_id int, endereco_id int, constraint pk_bibliotecario primary key (cib), constraint fk1_bibliotecario foreign key (cidade_id) references cidade(id) on delete set null, constraint fk2_bibliotecario foreign key (endereco_id) references endereco(id) on delete set null ); create table grupo ( nome_grupo varchar2(40) not null, tipo_grupo varchar2(10) not null, pontuacao_minima number not null, criado_por varchar2(100) not null, constraint pk_grupo primary key (nome_grupo,tipo_grupo), constraint fk_grupo foreign key (criado_por) references administrador(email_adm), constraint ck_grupo check (tipo_grupo = 'DOADOR' or tipo_grupo = 'VOLUNTARIO' or tipo_grupo = 'DONATARIO') ); create table temporada ( data_inicial_temp date not null, duracao_temp number not null, constraint pk_temporada primary key (data_inicial_temp) ); create table livro_adm ( codigo_barras_la number not null, email_adm varchar2(100) not null, constraint pk_livro_adm primary key (codigo_barras_la) ); create table doador ( email_usuario_doador varchar2(100) not null, pontuacao_doador number not null, constraint pk_doador primary key (email_usuario_doador), constraint pf_doador foreign key (email_usuario_doador) references pessoa_fisica(email_usuario_pf) ); create table donatario ( email_usuario_donatario varchar2(100) not null, pontuacao_donatario number not null, constraint pk_donatario primary key (email_usuario_donatario), constraint pf_donatario foreign key (email_usuario_donatario) references pessoa_fisica(email_usuario_pf) ); create table voluntario ( email_usuario_voluntario varchar2(100) not null, pontuacao_voluntario number not null, constraint pk_voluntario primary key (email_usuario_voluntario), constraint pf_voluntario foreign key (email_usuario_voluntario) references pessoa_fisica(email_usuario_pf) ); create table livro_doador_pj ( codigo_barras_ldpj number not null, email_usuario_pj varchar2(100) not null, constraint pk_livro_doador_pj primary key (codigo_barras_ldpj), constraint fk1_livro_doador_pj foreign key (codigo_barras_ldpj) references livro (codigo_barras) on delete cascade, constraint fk2_livro_doador_pj foreign key (email_usuario_pj) references pessoa_juridica (email_usuario_pj) on delete set null ); create table pertence ( nome_grupo varchar2(40) not null, tipo_grupo varchar2(10) not null, temporada date not null, email_usuario_pf varchar2(100) not null, constraint pk_pertence primary key (nome_grupo, tipo_grupo, temporada, email_usuario_pf), constraint fk_pertence_grupo foreign key (nome_grupo, tipo_grupo) references grupo (nome_grupo, tipo_grupo) on delete cascade, constraint fk_pertence_temporada foreign key (temporada) references temporada(data_inicial_temp) on delete cascade, constraint fk_pertence_usuario foreign key (email_usuario_pf) references pessoa_fisica (email_usuario_pf) on delete cascade ); create table livro_doador ( codigo_barras_ld number not null, email_usuario_doador varchar2(100) not null, constraint pk_livro_doador primary key (codigo_barras_ld), constraint fk1_livro_doador foreign key (codigo_barras_ld) references livro (codigo_barras) on delete cascade, constraint fk2_livro_doador foreign key (email_usuario_doador) references doador (email_usuario_doador) on delete cascade ); create table doacao ( codigo_barras_ld number not null, data_horario_doacao timestamp not null, pontuacao_doacao number not null, bibliotecario_aprovador number, constraint pk_doacao primary key (codigo_barras_ld, data_horario_doacao), constraint fk1_doacao foreign key (codigo_barras_ld) references livro_doador (codigo_barras_ld) on delete cascade, constraint fk2_doacao foreign key (bibliotecario_aprovador) references bibliotecario(cib) on delete set null ); create table emprestimo ( email_usuario_donatario varchar2(100) not null, codigo_barras number not null, data_retirada date not null, data_devolucao date, cib number not null, constraint pk_emprestimo primary key (email_usuario_donatario,codigo_barras,data_retirada), constraint fk1_emprestimo foreign key (email_usuario_donatario) references donatario (email_usuario_donatario) on delete set null, constraint fk2_emprestimo foreign key (codigo_barras) references livro (codigo_barras) on delete set null, constraint fk3_emprestimo foreign key (cib) references bibliotecario (cib) on delete set null ); create table questao ( email_usuario_donatario varchar2(100) not null, codigo_barras number not null, data_retirada date not null, numero_identificador int not null, nivel int not null, pergunta varchar2(100) not null, solucao varchar2(150) not null, pontuacao number not null, constraint pk_questao primary key (email_usuario_donatario,codigo_barras,data_retirada,numero_identificador), constraint fk_questao foreign key (email_usuario_donatario,codigo_barras,data_retirada) references emprestimo (email_usuario_donatario,codigo_barras,data_retirada) on delete cascade ); create table livro_voluntario ( codigo_barras_lv number not null, email_usuario_voluntario varchar2(100) not null, constraint pk_livro_voluntario primary key (codigo_barras_lv), constraint fk1_livro_voluntario foreign key (codigo_barras_lv) references livro (codigo_barras) on delete cascade, constraint fk2_livro_voluntario foreign key (email_usuario_voluntario) references voluntario (email_usuario_voluntario) on delete cascade ); create table missao ( data_horario_missao timestamp not null, codigo_barras_lv number not null, pontuacao_missao number not null, adm_aprovador varchar2(100), constraint pk_missao primary key (data_horario_missao,codigo_barras_lv), constraint fk1_missao foreign key (codigo_barras_lv) references livro_voluntario (codigo_barras_lv) on delete cascade, constraint fk2_missao foreign key (adm_aprovador) references administrador (email_adm) on delete set null );<file_sep>package livro; public class Livro { private Integer codigoBarras; private String autor; private String titulo; private long isbn; private String edicao; private int condicao; private Origem origem; public void print() { System.out.println("Código de barras: " + codigoBarras + "\nTitulo: " + titulo + "\nAutor: " + autor + "\nEdição: " + edicao + " ISBN: " + isbn + "\nOrigem: " + origem.toString()); System.out.print("Condição: "); if (condicao == 1) System.out.println("Nova"); if (condicao == 2) System.out.println("Semi nova"); if (condicao == 3) System.out.println("Usada"); if (condicao == 4) System.out.println("Poucos desgastes"); } public Livro(Integer codigoBarras, String autor, String titulo, long isbn, String edicao, int condicao, Origem origem) throws Exception { if (codigoBarras == null || codigoBarras == 0) { throw new Exception("Código de barras é obrigatório"); } if (autor == null || autor.length() == 0 || autor.length() > 50) { throw new Exception("Autor é obrigatório e deve ter até 50 caracteres"); } if (titulo == null || titulo.length() == 0 || titulo.length() > 50) { throw new Exception("Título é obrigatório e deve ter até 50 caracateres"); } if (isbn == 0) { throw new Exception("ISBN é obrigatório"); } if (edicao == null || edicao.length() == 0 || edicao.length() > 30) { throw new Exception("Edição é obrigatória e deve ter até 30 caracteres"); } if (condicao > 4 || condicao < 1) { throw new Exception("Condição é obrigatória e deve ter valores entre 1 e 4"); } if (origem == null) { throw new Exception("Origem é obrigatória"); } this.codigoBarras = codigoBarras; this.autor = autor; this.titulo = titulo; this.isbn = isbn; this.edicao = edicao; this.condicao = condicao; this.origem = origem; } public Livro(Integer codigoBarras, String autor, String titulo, long isbn, String edicao, int condicao, Origem origem, boolean fromDatabase) { if (fromDatabase) { this.codigoBarras = codigoBarras; this.autor = autor; this.titulo = titulo; this.isbn = isbn; this.edicao = edicao; this.condicao = condicao; this.origem = origem; } } public Integer getCodigoBarras() { return codigoBarras; } public void setCodigoBarras(Integer codigoBarras) { this.codigoBarras = codigoBarras; } public String getAutor() { return autor; } public void setAutor(String autor) { this.autor = autor; } public String getTitulo() { return titulo; } public void setTitulo(String titulo) { this.titulo = titulo; } public long getIsbn() { return isbn; } public void setIsbn(Integer isbn) { this.isbn = isbn; } public String getEdicao() { return edicao; } public void setEdicao(String edicao) { this.edicao = edicao; } public int getCondicao() { return condicao; } public void setCondicao(int condicao) { this.condicao = condicao; } public Origem getOrigem() { return origem; } public void setOrigem(Origem origem) { this.origem = origem; } } <file_sep>package usuario.fisica.doador; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import cidade.Cidade; import conexao.Conexao; import endereco.Endereco; import livro.Livro; import livro.Origem; import usuario.Tipo; import usuario.fisica.Perfil; import usuario.fisica.voluntario.Voluntario; public class DoadorDAO { private Connection conn; private PreparedStatement pstm; private String sql; public DoadorDAO() { try { conn = Conexao.getInstance(); } catch (Exception e) { e.printStackTrace(); } } public int insert(Doador doador) { try { sql = "insert into doador (email_usuario_doador, pontuacao_doador) " + "values (?, ?)"; pstm = conn.prepareStatement(sql); pstm.setString(1, doador.getEmail()); pstm.setDouble(2, doador.getPontuacao()); pstm.execute(); pstm.close(); } catch (SQLException e) { if (e.getErrorCode() == 1) { System.out.println("E-mail jŠ cadastrado"); } else if (e.getErrorCode() == 2291) { System.out.println("Erro de chave estrangeira: e-mail inexistente"); } else { e.printStackTrace(); } return e.getErrorCode(); } return 0; } public List<Doador> select(boolean selectPessoaFisica, boolean selectUsuario, boolean selectLivros) { List<Doador> doadores = new ArrayList<Doador>(); try { StringBuilder sb = new StringBuilder(); sb.append("select * from doador D"); if (selectPessoaFisica) { sb.append(" join pessoa_fisica F on F.email_usuario_pf = D.email_usuario_doador"); } if (selectUsuario) { sb.append(" join usuario U on F.email_usuario_pf = U.email left join cidade C " + "on U.cidade_id = C.id left join endereco E on U.endereco_id = E.id"); } sql = sb.toString(); pstm = conn.prepareStatement(sql); ResultSet rs = pstm.executeQuery(); while (rs.next()) { Doador d = new Doador(rs.getString("email_usuario_doador"), rs.getDouble("pontuacao_doador")); if (selectPessoaFisica) { d.setNome(rs.getString("nome_usuario_pf")); d.setCpf(rs.getString("cpf_usuario_pf")); d.setRg(rs.getString("rg_usuario_pf")); d.setTelefone(rs.getString("telefone_usuario_pf")); sql = "select perfil from perfis where email_usuario_pf = ?"; pstm = conn.prepareStatement(sql); pstm.setString(1, d.getEmail()); ResultSet rsp = pstm.executeQuery(); List<Perfil> perfis = new ArrayList<Perfil>(); while (rsp.next()) { perfis.add(Perfil.valueOf(rsp.getString("perfil"))); } d.setPerfis(perfis); } if (selectUsuario) { d.setSenha(rs.getString("senha")); d.setTipo(Tipo.valueOf(rs.getString("tipo_usuario"))); if (rs.getInt("endereco_id") != 0) d.setEndereco(new Endereco(rs.getInt("endereco_id"), rs.getString("cep"), rs.getInt("numero"), rs.getString("rua"), rs.getString("bairro"), rs.getString("complemento"))); if (rs.getInt("cidade_id") != 0) { d.setCidade(new Cidade(rs.getInt("cidade_id"), rs.getString("nome_cidade"), rs.getString("uf_cidade"))); } } if (selectLivros) { sql = "select * from livro_doador join livro on codigo_barras_ld = codigo_barras where email_usuario_doador = ?"; pstm = conn.prepareStatement(sql); pstm.setString(1, d.getEmail()); ResultSet rsl = pstm.executeQuery(); List<Livro> livros = new ArrayList<Livro>(); while (rsl.next()) { livros.add(new Livro(rsl.getInt("codigo_barras"), rsl.getString("autor"), rsl.getString("titulo"), rsl.getLong("isbn"), rsl.getString("edicao"), rsl.getInt("condicao"), Origem.valueOf(rsl.getString("origem")), true)); } d.setLivros(livros); } doadores.add(d); } pstm.close(); } catch (SQLException e) { e.printStackTrace(); } return doadores; } public Doador selectByEmail(String email, boolean selectPessoaFisica, boolean selectUsuario, boolean selectLivros) { Doador d = null; try { StringBuilder sb = new StringBuilder(); sb.append("select * from doador D"); if (selectPessoaFisica) { sb.append(" join pessoa_fisica F on F.email_usuario_pf = D.email_usuario_doador"); } if (selectUsuario) { sb.append(" join usuario U on F.email_usuario_pf = U.email left join cidade C " + "on U.cidade_id = C.id left join endereco E on U.endereco_id = E.id"); } sb.append(" where D.email_usuario_doador = ?"); sql = sb.toString(); pstm = conn.prepareStatement(sql); pstm.setString(1, email); ResultSet rs = pstm.executeQuery(); if (!rs.next()) { return null; } d = new Doador(rs.getString("email_usuario_doador"), rs.getDouble("pontuacao_doador")); if (selectPessoaFisica) { d.setNome(rs.getString("nome_usuario_pf")); d.setCpf(rs.getString("cpf_usuario_pf")); d.setRg(rs.getString("rg_usuario_pf")); d.setTelefone(rs.getString("telefone_usuario_pf")); sql = "select perfil from perfis where email_usuario_pf = ?"; pstm = conn.prepareStatement(sql); pstm.setString(1, d.getEmail()); ResultSet rsp = pstm.executeQuery(); List<Perfil> perfis = new ArrayList<Perfil>(); while (rsp.next()) { perfis.add(Perfil.valueOf(rsp.getString("perfil"))); } d.setPerfis(perfis); } if (selectUsuario) { d.setSenha(rs.getString("senha")); d.setTipo(Tipo.valueOf(rs.getString("tipo_usuario"))); if (rs.getInt("endereco_id") != 0) d.setEndereco(new Endereco(rs.getInt("endereco_id"), rs.getString("cep"), rs.getInt("numero"), rs.getString("rua"), rs.getString("bairro"), rs.getString("complemento"))); if (rs.getInt("cidade_id") != 0) { d.setCidade( new Cidade(rs.getInt("cidade_id"), rs.getString("nome_cidade"), rs.getString("uf_cidade"))); } } if (selectLivros) { sql = "select * from livro_doador join livro on codigo_barras_ld = codigo_barras where email_usuario_doador = ?"; pstm = conn.prepareStatement(sql); pstm.setString(1, d.getEmail()); ResultSet rsl = pstm.executeQuery(); List<Livro> livros = new ArrayList<Livro>(); while (rsl.next()) { livros.add(new Livro(rs.getInt("codigo_barras"), rs.getString("autor"), rs.getString("titulo"), rs.getInt("isbn"), rs.getString("edicao"), rs.getInt("condicao"), Origem.valueOf(rs.getString("origem")), true)); } d.setLivros(livros); } pstm.close(); } catch (SQLException e) { e.printStackTrace(); } return d; } } <file_sep>package questao; import emprestimo.Emprestimo; public class Questao { private Emprestimo emprestimo; private int numeroIdentificador; private int nivel; private String pergunta; private String solucao; private double pontuacao; public Questao(Emprestimo emprestimo, int numeroIdentificador, int nivel, String pergunta, String solucao, double pontuacao) throws Exception { if (emprestimo == null) { throw new Exception("Empréstimo é obrigatório"); } if (numeroIdentificador <= 0) { throw new Exception("Número identificador é obrigatório"); } if (nivel <= 0) { throw new Exception("Nível é obrigatório"); } if (pergunta == null || pergunta.length() == 0 || pergunta.length() > 100) { throw new Exception("Pergunta é obrigatória e deve ter até 100 caracteres"); } if (solucao == null || solucao.length() == 0 || solucao.length() > 150) { throw new Exception("Solução é obrigatória e deve ter até 150 caracteres"); } if (pontuacao < 0) { throw new Exception("Pontuação é obrigatória"); } this.emprestimo = emprestimo; this.numeroIdentificador = numeroIdentificador; this.nivel = nivel; this.pergunta = pergunta; this.solucao = solucao; this.pontuacao = pontuacao; } public Questao(int numeroIdentificador, int nivel, String pergunta, String solucao, double pontuacao) { this.numeroIdentificador = numeroIdentificador; this.nivel = nivel; this.pergunta = pergunta; this.solucao = solucao; this.pontuacao = pontuacao; } public void print() { System.out.println("Número identificador: " + numeroIdentificador + "\nNivel: " + nivel + " Pergunta: " + pergunta + "\nSolução: " + solucao + " Pontuação: " + pontuacao); if (emprestimo != null) { System.out.println("Empréstimo"); emprestimo.print(); } } public Emprestimo getEmprestimo() { return emprestimo; } public void setEmprestimo(Emprestimo emprestimo) { this.emprestimo = emprestimo; } public int getNumeroIdentificador() { return numeroIdentificador; } public void setNumeroIdentificador(int numeroIdentificador) { this.numeroIdentificador = numeroIdentificador; } public int getNivel() { return nivel; } public void setNivel(int nivel) { this.nivel = nivel; } public String getPergunta() { return pergunta; } public void setPergunta(String pergunta) { this.pergunta = pergunta; } public String getSolucao() { return solucao; } public void setSolucao(String solucao) { this.solucao = solucao; } public double getPontuacao() { return pontuacao; } public void setPontuacao(double pontuacao) { this.pontuacao = pontuacao; } } <file_sep>package usuario; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import bibliotecario.Bibliotecario; import cidade.Cidade; import conexao.Conexao; import endereco.Endereco; public class UsuarioDAO { private Connection conn; private PreparedStatement pstm; private String sql; public UsuarioDAO() { try { conn = Conexao.getInstance(); } catch (Exception e) { e.printStackTrace(); } } public int insert(Usuario usuario) { try { sql = "insert into usuario (email, senha, cidade_id, endereco_id, tipo_usuario) " + "values (?, ?, ?, ?, ?)"; pstm = conn.prepareStatement(sql); pstm.setString(1, usuario.getEmail()); pstm.setString(2, usuario.getSenha()); pstm.setInt(3, usuario.getCidade().getId()); pstm.setInt(4, usuario.getEndereco().getId()); pstm.setString(5, usuario.getTipo().toString()); pstm.execute(); pstm.close(); } catch (SQLException e) { if (e.getErrorCode() == 1) { System.out.println("E-mail já cadastrado"); } else if (e.getErrorCode() == 2291) { System.out.println("Erro de chave estrangeira: Cidade ou endereço inexistente"); } else { e.printStackTrace(); } return e.getErrorCode(); } return 0; } public List<Usuario> select(boolean selectEndereco, boolean selectCidade) { List<Usuario> usuarios = new ArrayList<Usuario>(); try { StringBuilder sb = new StringBuilder(); sb.append("select * from usuario U"); if (selectEndereco) { sb.append(" left join endereco E on U.endereco_id = E.id"); } if (selectCidade) { sb.append(" left join cidade C on U.cidade_id = C.id"); } sql = sb.toString(); pstm = conn.prepareStatement(sql); ResultSet rs = pstm.executeQuery(); while (rs.next()) { Usuario usuario = new Usuario(rs.getString("email"), rs.getString("senha"), Tipo.valueOf(rs.getString("tipo_usuario"))); if (selectEndereco && rs.getInt("endereco_id") != 0) { usuario.setEndereco(new Endereco(rs.getInt("endereco_id"), rs.getString("cep"), rs.getInt("numero"), rs.getString("rua"), rs.getString("bairro"), rs.getString("complemento"))); } if (selectCidade && rs.getInt("cidade_id") != 0) { usuario.setCidade(new Cidade(rs.getInt("cidade_id"), rs.getString("nome_cidade"), rs.getString("uf_cidade"))); } usuarios.add(usuario); } pstm.close(); } catch (SQLException e) { e.printStackTrace(); } return usuarios; } public Usuario selectByEmail(String email, boolean selectCidade, boolean selectEndereco) { Usuario u = null; try { StringBuilder sb = new StringBuilder(); sb.append("select * from usuario U"); if (selectEndereco) { sb.append(" left join endereco E on U.endereco_id = E.id"); } if (selectCidade) { sb.append(" left join cidade C on U.cidade_id = C.id"); } sb.append(" where U.email = ?"); sql = sb.toString(); pstm = conn.prepareStatement(sql); pstm.setString(1, email); ResultSet rs = pstm.executeQuery(); if (!rs.next()) { return null; } u = new Usuario(rs.getString("email"), rs.getString("senha"), Tipo.valueOf(rs.getString("tipo_usuario"))); if (selectEndereco && rs.getInt("endereco_id") != 0) { u.setEndereco(new Endereco(rs.getInt("endereco_id"), rs.getString("cep"), rs.getInt("numero"), rs.getString("rua"), rs.getString("bairro"), rs.getString("complemento"))); } if (selectCidade && rs.getInt("cidade_id") != 0) { u.setCidade(new Cidade(rs.getInt("cidade_id"), rs.getString("nome_cidade"), rs.getString("uf_cidade"))); } pstm.close(); } catch (Exception e) { e.printStackTrace(); } return u; } } <file_sep>-- Busca média de pontuação por Grupo (Na temporada atual) -- Será utilizado para realizar, na aplicação, uma comparação entre a pontuação do usuário (no respectivo grupo) -- e a média do grupo na temporada atual. Isso dará um resultado indicando se o usuário está acima da média -- (obs: a consulta da pontuação do usuário é uma consulta a parte e não tem nada haver com essa, somente na comparação -- feita na aplicação). select g.nome_grupo, avg( case g.tipo_grupo when 'DOADOR' then (select pontuacao_doador from doador d where d.email_usuario_doador = p.email_usuario_pf) when 'DONATARIO' then (select pontuacao_donatario from donatario do where do.email_usuario_donatario = p.email_usuario_pf) when 'VOLUNTARIO' then (select pontuacao_voluntario from voluntario v where v.email_usuario_voluntario = p.email_usuario_pf) end ) as media from grupo g join pertence p on g.nome_grupo = p.nome_grupo and g.tipo_grupo = p.tipo_grupo join temporada t on p.temporada = t.data_inicial_temp join pessoa_fisica pf on p.email_usuario_pf = pf.email_usuario_pf where sysdate between p.temporada and (p.temporada + t.duracao_temp) group by g.nome_grupo, p.temporada; -- Busca por Quantidade de Livros que um doador doou no mês atual -- select pf.nome_usuario_pf, count(l.titulo) "QTD_LIVROS_POR_MES" from pessoa_fisica pf join doador d on pf.email_usuario_pf = d.email_usuario_doador join livro_doador ld on d.email_usuario_doador = ld.email_usuario_doador join livro l on ld.codigo_barras_ld = l.codigo_barras join doacao doa on doa.codigo_barras_ld = ld.codigo_barras_ld where (extract(month from sysdate) = extract(month from doa.data_horario_doacao)) and (extract(year from sysdate) = extract(year from doa.data_horario_doacao)) group by pf.nome_usuario_pf; -- Busca por Quantidade de Livros que um voluntário coletou no mês atual -- select pf.nome_usuario_pf, count(l.titulo) "QTD_LIVROS_POR_MES" from pessoa_fisica pf join voluntario v on pf.email_usuario_pf = v.email_usuario_voluntario join livro_voluntario lv on v.email_usuario_voluntario = lv.email_usuario_voluntario join livro l on lv.codigo_barras_lv = l.codigo_barras join missao m on m.codigo_barras_lv = lv.codigo_barras_lv where (extract(month from sysdate) = extract(month from m.data_horario_missao)) and (extract(year from sysdate) = extract(year from m.data_horario_missao)) group by pf.nome_usuario_pf; -- Busca a média de livros doados no mês atual select avg(qtd_livros_por_mes) as media_livros_doados_por_mes from ( select pf.nome_usuario_pf, count(l.titulo) "QTD_LIVROS_POR_MES" from pessoa_fisica pf join doador d on pf.email_usuario_pf = d.email_usuario_doador join livro_doador ld on d.email_usuario_doador = ld.email_usuario_doador join livro l on ld.codigo_barras_ld = l.codigo_barras join doacao doa on doa.codigo_barras_ld = ld.codigo_barras_ld where (extract(month from sysdate) = extract(month from doa.data_horario_doacao)) and (extract(year from sysdate) = extract(year from doa.data_horario_doacao)) group by pf.nome_usuario_pf ); -- Busca a média de livros coletados no mês atual select avg(qtd_livros_por_mes) as media_livros_doados_por_mes from ( select pf.nome_usuario_pf, count(l.titulo) "QTD_LIVROS_POR_MES" from pessoa_fisica pf join voluntario v on pf.email_usuario_pf = v.email_usuario_voluntario join livro_voluntario lv on v.email_usuario_voluntario = lv.email_usuario_voluntario join livro l on lv.codigo_barras_lv = l.codigo_barras join missao m on m.codigo_barras_lv = lv.codigo_barras_lv where (extract(month from sysdate) = extract(month from m.data_horario_missao)) and (extract(year from sysdate) = extract(year from m.data_horario_missao)) group by pf.nome_usuario_pf ); -- Busca a média de pontuação de um doador por doações realizadas no mês atual select d.email_usuario_doador, avg(pontuacao_doacao) as media from doador d join livro_doador ld on d.email_usuario_doador = ld.email_usuario_doador join doacao doa on ld.codigo_barras_ld = doa.codigo_barras_ld where (extract(month from sysdate) = extract(month from doa.data_horario_doacao)) and (extract(year from sysdate) = extract(year from doa.data_horario_doacao)) group by d.email_usuario_doador; -- Busca média geral de pontuação de doação no mês atual select avg(pontuacao_doacao) as media from doacao doa where (extract(month from sysdate) = extract(month from doa.data_horario_doacao)) and (extract(year from sysdate) = extract(year from doa.data_horario_doacao)); -- Busca a média de pontuação de um voluntário por coletas realizadas no mês atual select v.email_usuario_voluntario, avg(pontuacao_missao) as media from voluntario v join livro_voluntario lv on v.email_usuario_voluntario = lv.email_usuario_voluntario join missao m on lv.codigo_barras_lv = m.codigo_barras_lv where (extract(month from sysdate) = extract(month from m.data_horario_missao)) and (extract(year from sysdate) = extract(year from m.data_horario_missao)) group by v.email_usuario_voluntario; -- where (extract(month from to_date('01/11/2020', 'dd/mm/yyyy')) = extract(month from doa.data_horario_doacao)) -- and (extract(year from to_date('01/11/2020', 'dd/mm/yyyy')) = extract(year from doa.data_horario_doacao)) -- Busca média geral de pontuação de doação no mês atual select avg(pontuacao_missao) as media from missao m where (extract(month from sysdate) = extract(month from m.data_horario_missao)) and (extract(year from sysdate) = extract(year from m.data_horario_missao)); -- Busca a média de pontuação de um donatário por pontuações conquistadas no mês atual select don.email_usuario_donatario, avg(q.pontuacao) as media from donatario don join emprestimo e on don.email_usuario_donatario = e.email_usuario_donatario join questao q on (q.email_usuario_donatario = e.email_usuario_donatario and q.codigo_barras = e.codigo_barras and q.data_retirada = e.data_retirada) where (extract(month from sysdate) = extract(month from e.data_devolucao)) and (extract(year from sysdate) = extract(year from e.data_devolucao)) group by don.email_usuario_donatario; -- Busca média geral de pontuação de questões no mês atual select avg(q.pontuacao) as media from emprestimo e join questao q on (q.email_usuario_donatario = e.email_usuario_donatario and q.codigo_barras = e.codigo_barras and q.data_retirada = e.data_retirada) where (extract(month from sysdate) = extract(month from e.data_devolucao)) and (extract(year from sysdate) = extract(year from e.data_devolucao)); -- Mostra a classificação geral dentro de um grupo (na aplicação você pode escolher o grupo para -- mostrar su classificação) select pf.nome_usuario_pf, case p.tipo_grupo when 'DOADOR' then (select pontuacao_doador from doador d where d.email_usuario_doador = p.email_usuario_pf) when 'DONATARIO' then (select pontuacao_donatario from donatario do where do.email_usuario_donatario = p.email_usuario_pf) when 'VOLUNTARIO' then (select pontuacao_voluntario from voluntario v where v.email_usuario_voluntario = p.email_usuario_pf) end as pontuacao from pertence p join temporada t on p.temporada = t.data_inicial_temp join pessoa_fisica pf on p.email_usuario_pf = pf.email_usuario_pf where sysdate between p.temporada and (p.temporada + t.duracao_temp) and p.nome_grupo = 'O melhor voluntariado' order by p.nome_grupo asc, pontuacao desc; -- Busca a média de pontuação por temporada select p.temporada, round(avg( case p.tipo_grupo when 'DOADOR' then (select pontuacao_doador from doador d where d.email_usuario_doador = p.email_usuario_pf) when 'DONATARIO' then (select pontuacao_donatario from donatario do where do.email_usuario_donatario = p.email_usuario_pf) when 'VOLUNTARIO' then (select pontuacao_voluntario from voluntario v where v.email_usuario_voluntario = p.email_usuario_pf) end ), 2) as media from pertence p join temporada t on p.temporada = t.data_inicial_temp join pessoa_fisica pf on p.email_usuario_pf = pf.email_usuario_pf group by p.temporada;<file_sep>package doacao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import bibliotecario.Bibliotecario; import conexao.Conexao; import livro.Livro; import livro.Origem; public class DoacaoDAO { private Connection conn; private PreparedStatement pstm; private String sql; public DoacaoDAO() { try { conn = Conexao.getInstance(); } catch (Exception e) { e.printStackTrace(); } } public void insert(Doacao doacao) { try { sql = "insert into doacao " + "(codigo_barras_ld, data_horario_doacao, pontuacao_doacao, bibliotecario_aprovador) " + "values (?, ?, ?, ?)"; pstm = conn.prepareStatement(sql); pstm.setInt(1, doacao.getLivro().getCodigoBarras()); pstm.setTimestamp(2, Timestamp.from(doacao.getDataHora())); pstm.setDouble(3, doacao.getPontuacao()); pstm.setInt(4, doacao.getBibliotecario().getCib()); pstm.execute(); pstm.close(); } catch (SQLException e) { e.printStackTrace(); } } public List<Doacao> select(boolean selectLivro, boolean selectBibliotecario) { List<Doacao> doacoes = new ArrayList<Doacao>(); try { StringBuilder sb = new StringBuilder(); sb.append("select * from doacao D"); if (selectLivro) { sb.append(" join livro_doador L on D.codigo_barras_ld = L.codigo_barras_ld"); } if (selectBibliotecario) { sb.append(" left join bibliotecario B on D.bibliotecario_aprovador = B.cib"); } sql = sb.toString(); pstm = conn.prepareStatement(sql); ResultSet rs = pstm.executeQuery(); while (rs.next()) { Doacao d = new Doacao(rs.getTimestamp("data_horario_doacao").toInstant(), rs.getDouble("pontuacao_doacao")); if (selectLivro) { d.setLivro(new Livro(rs.getInt("codigo_barras"), rs.getString("autor"), rs.getString("titulo"), rs.getInt("isbn"), rs.getString("edicao"), rs.getInt("condicao"), Origem.valueOf(rs.getString("origem")), true)); } if (selectBibliotecario) { d.setBibliotecario(new Bibliotecario(rs.getInt("cib"), rs.getString("senha_bibliotecario"), rs.getString("nome_bibliotecario"))); } doacoes.add(d); } pstm.close(); } catch (SQLException e) { e.printStackTrace(); } return doacoes; } } <file_sep>package temporada; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import conexao.Conexao; public class TemporadaDAO { private Connection conn; private PreparedStatement pstm; private String sql; public TemporadaDAO() { try { conn = Conexao.getInstance(); } catch (Exception e) { e.printStackTrace(); } } public int insert(Temporada temporada) { try { sql = "insert into temporada (data_inicial_temp, duracao_temp) " + "values (?, ?)"; pstm = conn.prepareStatement(sql); pstm.setDate(1, java.sql.Date.valueOf(temporada.getDataInicial())); pstm.setInt(2, temporada.getDuracao()); pstm.execute(); pstm.close(); } catch (SQLException e) { if (e.getErrorCode() == 1) { System.out.println("Temporada jŠ existe"); } else { e.printStackTrace(); } return e.getErrorCode(); } return 0; } public List<Temporada> select() { List<Temporada> temporadas = new ArrayList<Temporada>(); try { sql = "select * from temporada"; pstm = conn.prepareStatement(sql); ResultSet rs = pstm.executeQuery(); while (rs.next()) { Temporada t = new Temporada(rs.getDate("data_inicial_temp").toLocalDate(), rs.getInt("duracao_temp"), true); temporadas.add(t); } pstm.close(); } catch (SQLException e) { e.printStackTrace(); } return temporadas; } } <file_sep>package usuario.fisica.voluntario; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import cidade.Cidade; import conexao.Conexao; import endereco.Endereco; import livro.Livro; import livro.Origem; import usuario.Tipo; import usuario.fisica.Perfil; import usuario.fisica.PessoaFisica; public class VoluntarioDAO { private Connection conn; private PreparedStatement pstm; private String sql; public VoluntarioDAO() { try { conn = Conexao.getInstance(); } catch (Exception e) { e.printStackTrace(); } } public int insert(Voluntario voluntario) { try { sql = "insert into voluntario (email_usuario_voluntario, pontuacao_voluntario) " + "values (?, ?)"; pstm = conn.prepareStatement(sql); pstm.setString(1, voluntario.getEmail()); pstm.setDouble(2, voluntario.getPontuacao()); pstm.execute(); pstm.close(); } catch (SQLException e) { if (e.getErrorCode() == 1) { System.out.println("E-mail jŠ cadastrado"); } else if (e.getErrorCode() == 2291) { System.out.println("Erro de chave estrangeira: e-mail inexistente"); } else { e.printStackTrace(); } return e.getErrorCode(); } return 0; } public List<Voluntario> select(boolean selectPessoaFisica, boolean selectUsuario, boolean selectLivros) { List<Voluntario> voluntarios = new ArrayList<Voluntario>(); try { StringBuilder sb = new StringBuilder(); sb.append("select * from voluntario V"); if (selectPessoaFisica) { sb.append(" join pessoa_fisica F on F.email_usuario_pf = V.email_usuario_voluntario"); } if (selectUsuario) { sb.append(" join usuario U on F.email_usuario_pf = U.email left join cidade C " + "on U.cidade_id = C.id left join endereco E on U.endereco_id = E.id"); } sql = sb.toString(); pstm = conn.prepareStatement(sql); ResultSet rs = pstm.executeQuery(); while (rs.next()) { Voluntario v = new Voluntario(rs.getString("email_usuario_voluntario"), rs.getDouble("pontuacao_voluntario")); if (selectPessoaFisica) { v.setNome(rs.getString("nome_usuario_pf")); v.setCpf(rs.getString("cpf_usuario_pf")); v.setRg(rs.getString("rg_usuario_pf")); v.setTelefone(rs.getString("telefone_usuario_pf")); sql = "select perfil from perfis where email_usuario_pf = ?"; pstm = conn.prepareStatement(sql); pstm.setString(1, v.getEmail()); ResultSet rsp = pstm.executeQuery(); List<Perfil> perfis = new ArrayList<Perfil>(); while (rsp.next()) { perfis.add(Perfil.valueOf(rsp.getString("perfil"))); } v.setPerfis(perfis); } if (selectUsuario) { v.setSenha(rs.getString("senha")); v.setTipo(Tipo.valueOf(rs.getString("tipo_usuario"))); if (rs.getInt("endereco_id") != 0) v.setEndereco(new Endereco(rs.getInt("endereco_id"), rs.getString("cep"), rs.getInt("numero"), rs.getString("rua"), rs.getString("bairro"), rs.getString("complemento"))); if (rs.getInt("cidade_id") != 0) { v.setCidade(new Cidade(rs.getInt("cidade_id"), rs.getString("nome_cidade"), rs.getString("uf_cidade"))); } } if (selectLivros) { sql = "select * from livro_voluntario join livro on codigo_barras_lv = codigo_barras where email_usuario_voluntario = ?"; pstm = conn.prepareStatement(sql); pstm.setString(1, v.getEmail()); ResultSet rsl = pstm.executeQuery(); List<Livro> livros = new ArrayList<Livro>(); while (rsl.next()) { livros.add(new Livro(rsl.getInt("codigo_barras"), rsl.getString("autor"), rsl.getString("titulo"), rsl.getLong("isbn"), rsl.getString("edicao"), rsl.getInt("condicao"), Origem.valueOf(rsl.getString("origem")), true)); } v.setLivros(livros); } voluntarios.add(v); } pstm.close(); } catch (SQLException e) { e.printStackTrace(); } return voluntarios; } public Voluntario selectByEmail(String email, boolean selectPessoaFisica, boolean selectUsuario, boolean selectLivros) { Voluntario v = null; try { StringBuilder sb = new StringBuilder(); sb.append("select * from voluntario V"); if (selectPessoaFisica) { sb.append(" join pessoa_fisica F on F.email_usuario_pf = V.email_usuario_voluntario"); } if (selectUsuario) { sb.append(" join usuario U on F.email_usuario_pf = U.email left join cidade C " + "on U.cidade_id = C.id left join endereco E on U.endereco_id = E.id"); } sb.append(" where V.email_usuario_voluntario = ?"); sql = sb.toString(); pstm = conn.prepareStatement(sql); pstm.setString(1, email); ResultSet rs = pstm.executeQuery(); if (!rs.next()) { return null; } v = new Voluntario(rs.getString("email_usuario_voluntario"), rs.getDouble("pontuacao_voluntario")); if (selectPessoaFisica) { v.setNome(rs.getString("nome_usuario_pf")); v.setCpf(rs.getString("cpf_usuario_pf")); v.setRg(rs.getString("rg_usuario_pf")); v.setTelefone(rs.getString("telefone_usuario_pf")); sql = "select perfil from perfis where email_usuario_pf = ?"; pstm = conn.prepareStatement(sql); pstm.setString(1, v.getEmail()); ResultSet rsp = pstm.executeQuery(); List<Perfil> perfis = new ArrayList<Perfil>(); while (rsp.next()) { perfis.add(Perfil.valueOf(rsp.getString("perfil"))); } v.setPerfis(perfis); } if (selectUsuario) { v.setSenha(rs.getString("senha")); v.setTipo(Tipo.valueOf(rs.getString("tipo_usuario"))); if (rs.getInt("endereco_id") != 0) v.setEndereco(new Endereco(rs.getInt("endereco_id"), rs.getString("cep"), rs.getInt("numero"), rs.getString("rua"), rs.getString("bairro"), rs.getString("complemento"))); if (rs.getInt("cidade_id") != 0) { v.setCidade( new Cidade(rs.getInt("cidade_id"), rs.getString("nome_cidade"), rs.getString("uf_cidade"))); } } if (selectLivros) { sql = "select * from livro_voluntario join livro on codigo_barras_lv = codigo_barras where email_usuario_voluntario = ?"; pstm = conn.prepareStatement(sql); pstm.setString(1, v.getEmail()); ResultSet rsl = pstm.executeQuery(); List<Livro> livros = new ArrayList<Livro>(); while (rsl.next()) { livros.add(new Livro(rs.getInt("codigo_barras"), rs.getString("autor"), rs.getString("titulo"), rs.getInt("isbn"), rs.getString("edicao"), rs.getInt("condicao"), Origem.valueOf(rs.getString("origem")), true)); } v.setLivros(livros); } pstm.close(); } catch (SQLException e) { e.printStackTrace(); } return v; } } <file_sep>package bibliotecario; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import cidade.Cidade; import conexao.Conexao; import endereco.Endereco; public class BibliotecarioDAO { private Connection conn; private PreparedStatement pstm; private String sql; public BibliotecarioDAO() { try { conn = Conexao.getInstance(); } catch (Exception e) { e.printStackTrace(); } } public int insert(Bibliotecario bibliotecario) { try { if (bibliotecario.getEndereco() != null && bibliotecario.getCidade() != null) { sql = "insert into bibliotecario " + "(cib, senha_bibliotecario, nome_bibliotecario, cidade_id, endereco_id)" + "values (?, ?, ?, ?, ?)"; pstm = conn.prepareStatement(sql); pstm.setInt(1, bibliotecario.getCib()); pstm.setString(2, bibliotecario.getSenha()); pstm.setString(3, bibliotecario.getNome()); pstm.setInt(4, bibliotecario.getCidade().getId()); pstm.setInt(5, bibliotecario.getEndereco().getId()); } else if (bibliotecario.getEndereco() != null) { sql = "insert into bibliotecario " + "(cib, senha_bibliotecario, nome_bibliotecario, endereco_id)" + "values (?, ?, ?, ?)"; pstm = conn.prepareStatement(sql); pstm.setInt(1, bibliotecario.getCib()); pstm.setString(2, bibliotecario.getSenha()); pstm.setString(3, bibliotecario.getNome()); pstm.setInt(4, bibliotecario.getEndereco().getId()); } else if (bibliotecario.getCidade() != null) { sql = "insert into bibliotecario " + "(cib, senha_bibliotecario, nome_bibliotecario, cidade_id)" + "values (?, ?, ?, ?)"; pstm = conn.prepareStatement(sql); pstm.setInt(1, bibliotecario.getCib()); pstm.setString(2, bibliotecario.getSenha()); pstm.setString(3, bibliotecario.getNome()); pstm.setInt(4, bibliotecario.getCidade().getId()); } else { sql = "insert into bibliotecario " + "(cib, senha_bibliotecario, nome_bibliotecario)" + "values (?, ?, ?)"; pstm = conn.prepareStatement(sql); pstm.setInt(1, bibliotecario.getCib()); pstm.setString(2, bibliotecario.getSenha()); pstm.setString(3, bibliotecario.getNome()); } pstm.execute(); pstm.close(); } catch (SQLException e) { if (e.getErrorCode() == 1) { System.out.println("CIB já cadastrado"); } else if (e.getErrorCode() == 2291) { System.out.println("Erro de chave estrangeira - Cidade ou Endereço inexistentes"); } else { e.printStackTrace(); } return e.getErrorCode(); } return 0; } public List<Bibliotecario> select(boolean selectEndereco, boolean selectCidade) { List<Bibliotecario> bibliotecarios = new ArrayList<Bibliotecario>(); try { StringBuilder sb = new StringBuilder(); sb.append("select * from bibliotecario B"); if (selectEndereco) { sb.append(" left join endereco E on B.endereco_id = E.id"); } if (selectCidade) { sb.append(" left join cidade C on B.cidade_id = C.id"); } sql = sb.toString(); pstm = conn.prepareStatement(sql); ResultSet rs = pstm.executeQuery(); while (rs.next()) { Bibliotecario bibliotecario = new Bibliotecario(rs.getInt("cib"), rs.getString("senha_bibliotecario"), rs.getString("nome_bibliotecario")); if (selectEndereco && rs.getInt(5) != 0) { bibliotecario.setEndereco(new Endereco(rs.getInt(5), rs.getString("cep"), rs.getInt("numero"), rs.getString("rua"), rs.getString("bairro"), rs.getString("complemento"))); } if (selectCidade && rs.getInt(4) != 0) { bibliotecario.setCidade( new Cidade(rs.getInt(4), rs.getString("nome_cidade"), rs.getString("uf_cidade"))); } bibliotecarios.add(bibliotecario); } pstm.close(); } catch (SQLException e) { e.printStackTrace(); } return bibliotecarios; } public Bibliotecario selectByCIB(int cib, boolean selectEndereco, boolean selectCidade) { Bibliotecario bibliotecario = null; try { StringBuilder sb = new StringBuilder(); sb.append("select * from bibliotecario B"); if (selectEndereco) { sb.append(" left join endereco E on B.endereco_id = E.id"); } if (selectCidade) { sb.append(" left join cidade C on B.cidade_id = C.id"); } sb.append(" where B.cib = ?"); sql = sb.toString(); pstm = conn.prepareStatement(sql); pstm.setInt(1, cib); ResultSet rs = pstm.executeQuery(); if (!rs.next()) { return null; } bibliotecario = new Bibliotecario(rs.getInt("cib"), rs.getString("senha_bibliotecario"), rs.getString("nome_bibliotecario")); if (selectEndereco && rs.getInt(5) != 0) { bibliotecario.setEndereco(new Endereco(rs.getInt(5), rs.getString("cep"), rs.getInt("numero"), rs.getString("rua"), rs.getString("bairro"), rs.getString("complemento"))); } if (selectCidade && rs.getInt(4) != 0) { bibliotecario .setCidade(new Cidade(rs.getInt(4), rs.getString("nome_cidade"), rs.getString("uf_cidade"))); } pstm.close(); } catch (SQLException e) { e.printStackTrace(); } return bibliotecario; } } <file_sep>package grupo; import temporada.Temporada; import usuario.fisica.PessoaFisica; public class PessoaGrupoTemporada { private Grupo grupo; private Temporada temporada; private PessoaFisica pessoaFisica; public PessoaGrupoTemporada(Grupo grupo, Temporada temporada, PessoaFisica pessoaFisica) { this.grupo = grupo; this.temporada = temporada; this.pessoaFisica = pessoaFisica; } public void print() { grupo.print(); temporada.print(); pessoaFisica.print(); } public Grupo getGrupo() { return grupo; } public void setGrupo(Grupo grupo) { this.grupo = grupo; } public Temporada getTemporada() { return temporada; } public void setTemporada(Temporada temporada) { this.temporada = temporada; } public PessoaFisica getPessoaFisica() { return pessoaFisica; } public void setPessoaFisica(PessoaFisica pessoaFisica) { this.pessoaFisica = pessoaFisica; } } <file_sep>package usuario.fisica.donatario; import java.util.List; import cidade.Cidade; import endereco.Endereco; import usuario.Tipo; import usuario.fisica.Perfil; import usuario.fisica.PessoaFisica; public class Donatario extends PessoaFisica { private double pontuacao; public Donatario(String email, String nome, String cpf, String rg, String telefone) throws Exception { super(email, nome, cpf, rg, telefone); } public Donatario(String email, double pontuacao) { this.email = email; this.pontuacao = pontuacao; } public Donatario(String email, String senha, Cidade c, Endereco e, Tipo tipo, String nome, String cpf, String rg, String telefone, List<Perfil> perfis, double pontuacao) throws Exception { super(email, senha, c, e, tipo, nome, cpf, rg, telefone, perfis); this.pontuacao = pontuacao; } public void print() { super.print(); System.out.println("Pontuação: " + pontuacao); } public double getPontuacao() { return pontuacao; } public void setPontuacao(double pontuacao) { this.pontuacao = pontuacao; } } <file_sep>package main; import administrador.AdministradorDAO; import bibliotecario.BibliotecarioDAO; import cidade.CidadeDAO; import doacao.DoacaoDAO; import emprestimo.EmprestimoDAO; import endereco.EnderecoDAO; import grupo.GrupoDAO; import grupo.PessoaGrupoTemporadaDAO; import livro.LivroDAO; import questao.QuestaoDAO; import temporada.TemporadaDAO; import usuario.UsuarioDAO; import usuario.fisica.PerfilDAO; import usuario.fisica.PessoaFisicaDAO; import usuario.fisica.doador.DoadorDAO; import usuario.fisica.donatario.DonatarioDAO; import usuario.fisica.voluntario.VoluntarioDAO; import usuario.juridica.PessoaJuridicaDAO; /** * * Classe DAO * Essa classe implementa todos os DAO * Para evitar a criacao de muitos objetos diferentes * */ public class DAO { private AdministradorDAO administradorDAO; private BibliotecarioDAO bibliotecarioDAO; private CidadeDAO cidadeDAO; private DoacaoDAO doacaoDAO; private EmprestimoDAO emprestimoDAO; private EnderecoDAO enderecoDAO; private GrupoDAO grupoDAO; private LivroDAO livroDAO; private QuestaoDAO questaoDAO; private TemporadaDAO temporadaDAO; private UsuarioDAO usuarioDAO; private PessoaFisicaDAO pessoaFisicaDAO; private DoadorDAO doadorDAO; private DonatarioDAO donatarioDAO; private VoluntarioDAO voluntarioDAO; private PessoaJuridicaDAO pessoaJuridicaDAO; private PerfilDAO perfilDAO; private PessoaGrupoTemporadaDAO pessoaGrupoTemporadaDAO; private ConsultaDAO consultaDAO; public DAO() { administradorDAO = new AdministradorDAO(); bibliotecarioDAO = new BibliotecarioDAO(); cidadeDAO = new CidadeDAO(); doacaoDAO = new DoacaoDAO(); emprestimoDAO = new EmprestimoDAO(); enderecoDAO = new EnderecoDAO(); grupoDAO = new GrupoDAO(); livroDAO = new LivroDAO(); questaoDAO = new QuestaoDAO(); temporadaDAO = new TemporadaDAO(); usuarioDAO = new UsuarioDAO(); pessoaFisicaDAO = new PessoaFisicaDAO(); doadorDAO = new DoadorDAO(); donatarioDAO = new DonatarioDAO(); voluntarioDAO = new VoluntarioDAO(); pessoaJuridicaDAO = new PessoaJuridicaDAO(); perfilDAO = new PerfilDAO(); pessoaGrupoTemporadaDAO = new PessoaGrupoTemporadaDAO(); consultaDAO = new ConsultaDAO(); } public AdministradorDAO getAdministradorDAO() { return administradorDAO; } public void setAdministradorDAO(AdministradorDAO administradorDAO) { this.administradorDAO = administradorDAO; } public BibliotecarioDAO getBibliotecarioDAO() { return bibliotecarioDAO; } public void setBibliotecarioDAO(BibliotecarioDAO bibliotecarioDAO) { this.bibliotecarioDAO = bibliotecarioDAO; } public CidadeDAO getCidadeDAO() { return cidadeDAO; } public void setCidadeDAO(CidadeDAO cidadeDAO) { this.cidadeDAO = cidadeDAO; } public DoacaoDAO getDoacaoDAO() { return doacaoDAO; } public void setDoacaoDAO(DoacaoDAO doacaoDAO) { this.doacaoDAO = doacaoDAO; } public EmprestimoDAO getEmprestimoDAO() { return emprestimoDAO; } public void setEmprestimoDAO(EmprestimoDAO emprestimoDAO) { this.emprestimoDAO = emprestimoDAO; } public EnderecoDAO getEnderecoDAO() { return enderecoDAO; } public void setEnderecoDAO(EnderecoDAO enderecoDAO) { this.enderecoDAO = enderecoDAO; } public GrupoDAO getGrupoDAO() { return grupoDAO; } public void setGrupoDAO(GrupoDAO grupoDAO) { this.grupoDAO = grupoDAO; } public LivroDAO getLivroDAO() { return livroDAO; } public void setLivroDAO(LivroDAO livroDAO) { this.livroDAO = livroDAO; } public QuestaoDAO getQuestaoDAO() { return questaoDAO; } public void setQuestaoDAO(QuestaoDAO questaoDAO) { this.questaoDAO = questaoDAO; } public TemporadaDAO getTemporadaDAO() { return temporadaDAO; } public void setTemporadaDAO(TemporadaDAO temporadaDAO) { this.temporadaDAO = temporadaDAO; } public UsuarioDAO getUsuarioDAO() { return usuarioDAO; } public void setUsuarioDAO(UsuarioDAO usuarioDAO) { this.usuarioDAO = usuarioDAO; } public PessoaFisicaDAO getPessoaFisicaDAO() { return pessoaFisicaDAO; } public void setPessoaFisicaDAO(PessoaFisicaDAO pessoaFisicaDAO) { this.pessoaFisicaDAO = pessoaFisicaDAO; } public DoadorDAO getDoadorDAO() { return doadorDAO; } public void setDoadorDAO(DoadorDAO doadorDAO) { this.doadorDAO = doadorDAO; } public DonatarioDAO getDonatarioDAO() { return donatarioDAO; } public void setDonatarioDAO(DonatarioDAO donatarioDAO) { this.donatarioDAO = donatarioDAO; } public VoluntarioDAO getVoluntarioDAO() { return voluntarioDAO; } public void setVoluntarioDAO(VoluntarioDAO voluntarioDAO) { this.voluntarioDAO = voluntarioDAO; } public PessoaJuridicaDAO getPessoaJuridicaDAO() { return pessoaJuridicaDAO; } public void setPessoaJuridicaDAO(PessoaJuridicaDAO pessoaJuridicaDAO) { this.pessoaJuridicaDAO = pessoaJuridicaDAO; } public PerfilDAO getPerfilDAO() { return perfilDAO; } public void setPerfilDAO(PerfilDAO perfilDAO) { this.perfilDAO = perfilDAO; } public PessoaGrupoTemporadaDAO getPessoaGrupoTemporadaDAO() { return pessoaGrupoTemporadaDAO; } public void setPessoaGrupoTemporadaDAO(PessoaGrupoTemporadaDAO pessoaGrupoTemporadaDAO) { this.pessoaGrupoTemporadaDAO = pessoaGrupoTemporadaDAO; } public ConsultaDAO getConsultaDAO() { return consultaDAO; } public void setConsultaDAO(ConsultaDAO consultaDAO) { this.consultaDAO = consultaDAO; } } <file_sep>package livro; public enum Origem { DOADOR, VOLUNTARIO, PESSOA_JURIDICA, ADMINISTRADOR } <file_sep>package usuario.juridica; import java.util.List; import cidade.Cidade; import endereco.Endereco; import livro.Livro; import usuario.Tipo; import usuario.Usuario; public class PessoaJuridica extends Usuario { private String razaoSocial; private String nomeFantasia; private String cnpj; private String inscricaoEstadual; private List<Livro> livros; public PessoaJuridica(String email, String senha, Cidade cidade, Endereco endereco, Tipo tipo, String razaoSocial, String nomeFantasia, String cnpj, String inscricaoEstadual) throws Exception { super(email, senha, cidade, endereco, tipo); this.razaoSocial = razaoSocial; this.nomeFantasia = nomeFantasia; this.cnpj = cnpj; this.inscricaoEstadual = inscricaoEstadual; } public PessoaJuridica(String email, String razaoSocial, String nomeFantasia, String cnpj, String inscricaoEstadual) { this.email = email; this.razaoSocial = razaoSocial; this.nomeFantasia = nomeFantasia; this.cnpj = cnpj; this.inscricaoEstadual = inscricaoEstadual; } public void print() { super.print(); System.out.println("Razão social: " + this.razaoSocial + "\nCNPJ: " + this.cnpj + " Inscrição estadual: " + this.inscricaoEstadual + "\nNome fantasia: " + this.nomeFantasia); if (livros != null && this.livros.size() > 0) { System.out.println("Livros doados: "); for (Livro livro : livros) { livro.print(); } } } public String getRazaoSocial() { return razaoSocial; } public void setRazaoSocial(String razaoSocial) { this.razaoSocial = razaoSocial; } public String getNomeFantasia() { return nomeFantasia; } public void setNomeFantasia(String nomeFantasia) { this.nomeFantasia = nomeFantasia; } public String getCnpj() { return cnpj; } public void setCnpj(String cnpj) { this.cnpj = cnpj; } public String getInscricaoEstadual() { return inscricaoEstadual; } public void setInscricaoEstadual(String inscricaoEstadual) { this.inscricaoEstadual = inscricaoEstadual; } public List<Livro> getLivros() { return livros; } public void setLivros(List<Livro> livros) { this.livros = livros; } } <file_sep>package usuario; public enum Tipo { PESSOA_FISICA, PESSOA_JURIDICA } <file_sep>package administrador; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import livro.Livro; public class Administrador { private String email; private String senha; private String nome; private LocalDate dataRegistro; private List<Livro> livros; public Administrador(String email, String senha, String nome) throws Exception { if (email == null || email.length() == 0 || email.length() > 100) { throw new Exception("E-mail é obrigatório e deve ter até 100 caracteres"); } Pattern pattern = Pattern.compile("^.+@.+\\..+$"); Matcher matcher = pattern.matcher(email); if (!matcher.matches()) { throw new Exception("E-mail inválido"); } if (senha == null || senha.length() == 0 || senha.length() > 20) { throw new Exception("Senha é obrigatória e deve ter até 20 caracteres"); } if (nome == null || nome.length() == 0 || nome.length() > 50) { throw new Exception("Nome é obrigatório e deve ter até 50 caracteres"); } this.email = email; this.senha = senha; this.nome = nome; this.dataRegistro = LocalDate.now(); this.livros = new ArrayList<Livro>(); } public Administrador(String email, String senha, String nome, LocalDate dataRegistro) { this.email = email; this.senha = senha; this.nome = nome; this.dataRegistro = dataRegistro; } public void print() { System.out.println("E-mail: " + this.email + "\nNome: " + this.nome + "\nData de registro: " + this.dataRegistro.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"))); if (this.livros != null && this.livros.size() > 0) { System.out.println("Lista de livros:"); for (Livro livro : livros) { livro.print(); } } } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = senha; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public LocalDate getDataRegistro() { return dataRegistro; } public void setDataRegistro(LocalDate dataRegistro) { this.dataRegistro = dataRegistro; } public List<Livro> getLivros() { return livros; } public void setLivros(List<Livro> livros) { this.livros = livros; } } <file_sep># BookDonations Project developed to Databases subject @ ICMC - USP <file_sep>package usuario.juridica; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import cidade.Cidade; import conexao.Conexao; import endereco.Endereco; import livro.Livro; import livro.Origem; import usuario.Tipo; import usuario.fisica.PessoaFisica; public class PessoaJuridicaDAO { private Connection conn; private PreparedStatement pstm; private String sql; public PessoaJuridicaDAO() { try { conn = Conexao.getInstance(); } catch (Exception e) { e.printStackTrace(); } } public int insert(PessoaJuridica pessoaJuridica) { try { sql = "insert into pessoa_juridica " + "(email_usuario_pj, razao_social, nome_fantasia, cnpj_usuario_pj, " + "inscricao_estadual) " + "values (?, ?, ?, ?, ?)"; pstm = conn.prepareStatement(sql); pstm.setString(1, pessoaJuridica.getEmail()); pstm.setString(2, pessoaJuridica.getRazaoSocial()); pstm.setString(3, pessoaJuridica.getNomeFantasia()); pstm.setString(4, pessoaJuridica.getCnpj()); pstm.setString(5, pessoaJuridica.getInscricaoEstadual()); pstm.execute(); pstm.close(); } catch (SQLException e) { if (e.getErrorCode() == 1) { System.out.println("E-mail já cadastrado"); } else if (e.getErrorCode() == 2291) { System.out.println("Erro de chave estrangeira: usuário não cadastrado"); } else { e.printStackTrace(); } return e.getErrorCode(); } return 0; } public List<PessoaJuridica> select(boolean selectUsuario, boolean selectLivros) { List<PessoaJuridica> pessoas = new ArrayList<PessoaJuridica>(); try { StringBuilder sb = new StringBuilder(); sb.append("select * from pessoa_juridica J"); if (selectUsuario) { sb.append(" join usuario U on J.email_usuario_pj = U.email left join cidade C " + "on U.cidade_id = C.id left join endereco E on U.endereco_id = E.id"); } sql = sb.toString(); pstm = conn.prepareStatement(sql); ResultSet rs = pstm.executeQuery(); while (rs.next()) { PessoaJuridica pj = new PessoaJuridica(rs.getString("email_usuario_pj"), rs.getString("razao_social"), rs.getString("nome_fantasia"), rs.getString("cnpj_usuario_pj"), rs.getString("inscricao_estadual")); if (selectUsuario) { pj.setSenha(rs.getString("senha")); pj.setTipo(Tipo.valueOf(rs.getString("tipo_usuario"))); if (rs.getInt("endereco_id") != 0) pj.setEndereco(new Endereco(rs.getInt("endereco_id"), rs.getString("cep"), rs.getInt("numero"), rs.getString("rua"), rs.getString("bairro"), rs.getString("complemento"))); if (rs.getInt("cidade_id") != 0) { pj.setCidade(new Cidade(rs.getInt("cidade_id"), rs.getString("nome_cidade"), rs.getString("uf_cidade"))); } } if (selectLivros) { sql = "select * from livro_doador_pj join livro on codigo_barras_ldpj = codigo_barras where email_usuario_pj = ?"; pstm = conn.prepareStatement(sql); pstm.setString(1, pj.getEmail()); ResultSet rsl = pstm.executeQuery(); List<Livro> livros = new ArrayList<Livro>(); while (rsl.next()) { livros.add(new Livro(rs.getInt("codigo_barras"), rs.getString("autor"), rs.getString("titulo"), rs.getInt("isbn"), rs.getString("edicao"), rs.getInt("condicao"), Origem.valueOf(rs.getString("origem")), true)); } pj.setLivros(livros); } pessoas.add(pj); } pstm.close(); } catch (SQLException e) { e.printStackTrace(); } return pessoas; } } <file_sep>package endereco; public class Endereco { private Integer id; private String cep; private int numero; private String rua; private String bairro; private String complemento; public Endereco(String cep, int numero, String rua, String bairro, String complemento) throws Exception { if (cep == null || cep.length() != 9) { throw new Exception("O CEP é obrigatório e deve ser no formato 'XXXXX-XXX'"); } if (rua == null || rua.length() == 0) { throw new Exception("A rua é obrigatória"); } this.cep = cep; this.numero = numero; this.rua = rua; this.bairro = bairro; this.complemento = complemento; // TODO gerar id this.id = (int) (Math.random() * 100); } public Endereco(int id, String cep, int numero, String rua, String bairro, String complemento) { this.cep = cep; this.numero = numero; this.rua = rua; this.bairro = bairro; this.complemento = complemento; this.id = id; } public void print() { System.out.print("ID: " + this.id + "\nRua: " + this.rua); if (this.numero > 0) System.out.print(", " + this.numero); if (this.complemento != null && this.complemento.length() > 0) System.out.print(" " + this.complemento); if (this.bairro != null && this.bairro.length() > 0) System.out.println("\nBairro: " + this.bairro); System.out.println("\nCEP: " + this.cep); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCep() { return cep; } public void setCep(String cep) { this.cep = cep; } public int getNumero() { return numero; } public void setNumero(int numero) { this.numero = numero; } public String getRua() { return rua; } public void setRua(String rua) { this.rua = rua; } public String getBairro() { return bairro; } public void setBairro(String bairro) { this.bairro = bairro; } public String getComplemento() { return complemento; } public void setComplemento(String complemento) { this.complemento = complemento; } }
7ceb74b5216cf05e703443de533d33d562e72ddf
[ "Markdown", "Java", "SQL" ]
21
Java
arenasoy/BookDonations
e9ce98381eb44d10302d51a4f300f449592168e4
92a7f869f8afce2671c406cd52f4b30e388bea11
refs/heads/master
<repo_name>stphnVi/Got<file_sep>/Client/src/include/list.hpp #ifndef LIST_HPP #define LIST_HPP #include <string> #include <iostream> #include <sstream> #include <initializer_list> #include <memory> namespace ce { template <class T> class list; /** * @brief Node class used to store data in a doubly linked list * * @tparam T */ template <class T> class Node { private: friend class list<T>; explicit Node(T newdata) : data(newdata) {} public: std::shared_ptr<Node<T>> prev = nullptr; std::shared_ptr<Node<T>> next = nullptr; T data; /** * @brief * * @return std::string */ std::string toString() { std::stringstream ss; ss << data; return ss.str(); } template <class E> /** * @brief * * @param x * @param y * @return true * @return false */ friend bool operator==(const list<E> &x, const list<E> &y); }; /** * @brief allows for each iteration trough list elements * * @tparam T data type of list to be iterated over */ template <class T> struct listIterator { std::shared_ptr<Node<T>> n; listIterator<T>(std::shared_ptr<Node<T>> node) : n(node) {} //constructor bool operator!=(listIterator<T> rhs) { return n != rhs.n; } //Node<T> &operator*() { return *n; } T &operator*() { return n->data; } void operator++() { n = n->next; } void operator--() { n = n->prev; } }; template <class T> /** * @brief * */ class list { private: std::shared_ptr<Node<T>> first = nullptr; std::shared_ptr<Node<T>> last = nullptr; public: list(); explicit list(std::initializer_list<T> list); explicit list(int *list, int size); explicit list(T defaultValue, int size); //access /** * @brief gives an iterator pointing to the first element * * @return listIterator<T> */ listIterator<T> begin() { return first; }; /** * @brief gives an iterator pointing to the final element of the list * * @return listIterator<T> */ listIterator<T> end() { return last->next; }; T &at(int position); T &operator[](int position); T &front(); T &back(); //information bool empty(); bool contains(T data) const; int size() const; //modifiers int clear(); int insert(T data, int index); int erase(int index); int push_back(T data); int push_front(T data); T pop_back(); T pop_front(); int swap(int indexA, int indexB); std::string toString(); template <class E> friend bool operator==(list<E> &x, list<E> &y); //extra static list<T> getInverse(list<T> &toInvert); }; template <class T> list<T>::list(){}; /** * @brief Construct a new list<T>::list object based on an initializer list * * @tparam T type * @param list */ template <class T> list<T>::list(std::initializer_list<T> list) { for (T element : list) { push_back(element); } } /** * @brief Construct a new list<T>::list initialize a list based on a number matrix * * @tparam T * @param list * @param size */ template <class T> list<T>::list(int *list, int size) { for (int i = 0; i < size; i++) { push_back(list[i]); } } /** * @brief Construct a new list<T>::list with a default value given up to size * * @tparam T * @param defaultVal * @param size */ template <class T> list<T>::list(T defaultVal, int size) { for (int i = 0; i < size; i++) { push_back(defaultVal); } } /** * @brief gets element at index by reference * * @tparam T * @param index * @return T& */ template <class T> T &list<T>::at(int index) { int i = 0; std::shared_ptr<Node<T>> it = first; while (i != index) { ++i; it = it->next; if (it == nullptr) { throw 10; // invalid index exception } } return it->data; } /** * @brief gets element at index by reference * * @tparam T * @param index * @return T& */ template <class T> T &list<T>::operator[](int index) { return at(index); } /** * @brief returns first element data * * @tparam T * @return T& */ template <class T> T &list<T>::front() { return first->data; } /** * @brief returns las element data * * @tparam T * @return T& */ template <class T> T &list<T>::back() { return last->data; } /** * @brief returns is the list has elements or not * * @tparam T * @return true list has no elements * @return false list has at least one element */ template <class T> bool list<T>::empty() { return (first == nullptr); } /** * @brief checks if given data is stored in one of the list nodes * * @tparam T type * @param data data to look for * @return true list contains data * @return false list does not contain the data */ template <class T> bool list<T>::contains(T data) const { std::shared_ptr<Node<T>> it = first; while (it != nullptr) { if (it->data == data) { return true; } it = it->next; } return false; } /** * @brief gets the size of the list (amount of elements stored) * * @tparam T type * @return int size of list */ template <class T> int list<T>::size() const { int x = 0; std::shared_ptr<Node<T>> it = first; while (it != nullptr) { ++x; it = it->next; } return x; } //modifiers /** * @brief makes the list an empty list * * @tparam T * @return int error value */ template <class T> int list<T>::clear() { first = nullptr; last = nullptr; return 0; } /** * @brief inserts the data at the given position, pushed data to the end if the index overflows * * @tparam T type * @param data data that is to be inserted * @param index prefered insertion index * @return int error checking */ template <class T> int list<T>::insert(T data, int index) { if (index >= (size() - 1)) { //end or bigger than end push_back(data); } else if (index == 0) { //first element push_front(data); } else { //index in bounds std::shared_ptr<Node<T>> x(new Node<T>(data)); std::shared_ptr<Node<T>> front = first; int i = 0; while (i != index) { front = front->next; } std::shared_ptr<Node<T>> rear = front->prev; x->prev = rear; x->next = front; rear->next = x; front->prev = x; } return 0; } /** * @brief erases the element and the given index * * @tparam T type * @param index index to erase * @return int 0 if not error found, -1 if an error was found */ template <class T> int list<T>::erase(int index) { if (index > (size() - 1)) { return -1; } else if (index == 0) { pop_front(); } else if (index == (size() - 1)) { pop_back(); } else { std::shared_ptr<Node<T>> toDel = first; for (int i = 0; i < index; i++) { toDel = toDel->next; } toDel->prev->next = toDel->next; toDel->next->prev = toDel->prev; } return 0; } /** * @brief pushes element to the end of the list * * @tparam T type * @param data to be inserted * @return int error code */ template <class T> int list<T>::push_back(T data) { std::shared_ptr<Node<T>> x(new Node<T>(data)); if (empty()) { //empty first = last = x; } else { //not empty last->next = x; x->prev = last; last = x; } return 0; } /** * @brief pushes element to the beginning of the list * * @tparam T type * @param data o be added * @return int error code */ template <class T> int list<T>::push_front(T data) { std::shared_ptr<Node<T>> x(new Node<T>(data)); if (empty()) { //empty first = last = x; } else { //not empty first->prev = x; x->next = first; first = x; } return 0; } /** * @brief erases last element and returns it's value * * @tparam T type * @return T value stored in the erased node */ template <class T> T list<T>::pop_back() { T value = last->data; if (last->prev == nullptr) { first = last = nullptr; } else { std::shared_ptr<Node<T>> temp = last; last = temp->prev; last->next = nullptr; } return value; } /** * @brief erases first element an returns it's value * * @tparam T type * @return T value of erased node */ template <class T> T list<T>::pop_front() { T value = first->data; if (first->next == nullptr) { first = last = nullptr; } else { std::shared_ptr<Node<T>> temp = first; first = temp->next; first->prev = nullptr; } return value; } /** * @brief swaps the information betweeen to indexes * * @tparam T type * @param indexA index to be swapped for index B * @param indexB index to be swapped with indexA * @return int */ template <class T> int list<T>::swap(int indexA, int indexB) { T &a = at(indexA); T &b = at(indexB); T temp = a; a = b; b = temp; return 0; } /** * @brief gets list as an string value by sugin an stringstream * some data types might not be able to be printed this way * * @tparam T type * @return std::string list as a string */ template <class T> std::string list<T>::toString() { int n = size() - 1; std::shared_ptr<Node<T>> it = first; std::string stringForm = "["; for (int i = 0; i <= n; i++) { stringForm += (it->toString()); if (it->next != nullptr) { stringForm += ','; } it = it->next; } stringForm += ']'; return stringForm; } /** * @brief overload comparison operator to be able to check if two lists contain the same values * * @tparam T type * @param x list at the left * @param y list at the right * @return true both contain the same values * @return false both contain different values */ template <class T> bool operator==(list<T> &x, list<T> &y) { std::shared_ptr<Node<T>> itx = x.first; std::shared_ptr<Node<T>> ity = y.first; if (x.size() != y.size()) { return false; } while (itx != nullptr) { if (itx->data != ity->data) { return false; } itx = itx->next; ity = ity->next; } return true; } /** * @brief gets the reversed version of a given list * * @tparam T type * @param toInvert list to reverse * @return list<T> */ template<class T> list<T> list<T>::getInverse(list<T> &toInvert){ list<T> inverted; for (auto x :toInvert) { inverted.push_front(x); } return inverted; } }; // namespace ce #endif //SPIRITTEMPLE_LIST_HPP <file_sep>/tasks/buildEma.sh cd Client rm -rf build mkdir build cd build #cmake -DCMAKE_TOOLCHAIN_FILE=/home/stphn/vcpkg/scripts/buildsystems/vcpkg.cmake .. #cmake -DCMAKE_TOOLCHAIN_FILE=/usr/share/vcpkg/scripts/buildsystems/vcpkg.cmake .. cd .. cmake --build build/ --config Release cd .. Client/build/got echo "ponga en el build de su nombre en tasks/build la dirección de la vara de cmake"<file_sep>/Client/src/include/Interface.hpp #ifndef INTERFACE_H #define INTERFACE_H #include <stdlib.h> #include <iostream> #include "nlohmannJson.hpp" //got--> init <name>, help, add[-A] [name], commit <message>, //got-->status <file>, rollback <file> <commit>, reset <file>, sync <file> /** * @brief Clase que maneja la interface por comandos de la aplicacion Got * */ class Interface{ public: nlohmann::json filesAdded; // user void getCommand(int count, char * theCom[]); void sendComand(); //server void toClient(int count, char * theCom[]); void fromClient(); void createProject(int count, char * theCom[], int id); void handleCommitFile(); void handleAddFile(char * thecom[]); void back(char * theCom[]); }; #endif<file_sep>/Client/src/include/utilities.hpp #ifndef SPIRITTEMPLE_UTILITIES_HPP #define SPIRITTEMPLE_UTILITIES_HPP #include <iostream> namespace ce { template <class T> void log(T message, bool condition) { if (condition) std::cout << message << std::endl; } /** * @brief logger for relevant game information * * @tparam T * @param message */ template <class T> void log(T message) { std::cout << message << std::endl; } /** * @brief logger for relevant game information * @tparam T * @tparam T * @param messag */ template <class T, class E> void log(T message, E message2) { std::cout << message << message2 << std::endl; } /** * @brief logger for relevant game information * * @tparam T * @tparam T * @tparam T * @param message */ template <class T, class E, class J> void log(T message, E message2, J message3) { std::cout << message << message2 << message3 << std::endl; } /** * @brief logger for debugging sessions * * @tparam T * @param message */ template <class T> void debuglog(T message) { std::cout << message << std::endl; } /** * @brief logger for debugging sessions * * @tparam T * @tparam T * @param message */ template <class T, class E> void debuglog(T message, E message2) { std::cout << message << message2 << std::endl; } /** * @brief logger for debugging sessions * * @tparam T * @tparam T * @tparam T * @param message */ template <class T, class E, class J> void debuglog(T message, E message2, J message3) { std::cout << message << message2 << message3 << std::endl; } /** * @brief LAUNCHES AN ERROR AND PAUSES EXECUTION WITH A MESSAGE * * @tparam T * @param message */ template <class T> void errorlog(T message) { std::cerr << "Error, aborting process. Cause: " << message << std::endl; exit(EXIT_FAILURE); } /** * @brief LAUNCHES AN ERROR AND PAUSES EXECUTION WITH A MESSAGE * * @tparam T * @tparam T * @param message */ template <class T, class E> void errorlog(T message, E message2) { std::cout << message << message2 << std::endl; exit(EXIT_FAILURE); } /** * @brief LAUNCHES AN ERROR AND PAUSES EXECUTION WITH A MESSAGE * * @tparam T * @tparam T * @tparam T * @param message */ template <class T, class E, class J> void errorlog(T message, E message2, J message3) { std::cout << message << message2 << message3 << std::endl; exit(EXIT_FAILURE); } }; // namespace ce #endif<file_sep>/Server/src/Commit.js const compressor = require("./Huffman.js"); const DB = require("./DataBase.js").DataBase.Instance(); const md5 = require("md5"); const processChanges = require("./processChanges.js"); /** * Clase para ejecutar los commits de achivos realizados por el usuario */ class Commit { #isOpen; #commitId = 0; #encoder; /** * Representa un objeto de tipo Commit * @constructor */ constructor() { this.#encoder = new compressor.Huffman(); } /** * Realiza el commit en la base de datos y genera el ID mediante el algoritmo MD5 * @param {number} repoId - Identificador del repositorio * @param {string} parentCommit - Commit padre * @param {string | Buffer | number[]} mensaje - Mensaje del commit */ async open(repoId, parentCommit, mensaje) { this.#isOpen = true; this.#commitId = md5(`${repoId}::${parentCommit}::${mensaje}::${Date.now()}`) await DB.insertCommit(this.#commitId, repoId, parentCommit, mensaje); return this.#commitId; } /** * Cierra el commit y retorna el ID del mismo */ close() { this.#isOpen = false; return this.#commitId; } /** * Inserta un archivo comprimido en la base de datos * @param {string} ruta - Ruta del archivo por guardar * @param {string} contenido - Contenido del archivo */ async insertArchivo(ruta, contenido) { if (!this.#isOpen) { throw "there's no open commit" } let cont_codificado = this.#encoder.compress(contenido); await DB.insertArchivo(ruta, this.#commitId, cont_codificado.code, cont_codificado.tabla) } /** * Inserta los nuevos cambios en la base de datos siempre y cuando el commit este abierto */ async insertChange(ruta, newText) { if (!this.#isOpen) { throw "there's no open commit" } let oldText = await DB.getFileState(ruta); if (oldText != newText) { let change = JSON.stringify(processChanges.getDiff(ruta, oldText, newText)); DB.insertDiff(this.#commitId,ruta,change, newText); } } async checkIfLast(commit) { return await DB.checkIfIsLastCommit(commit); } /** * Define el estado del commit, si esta cerrado o abierto */ is_open() { return this.#isOpen } } module.exports.Commit = Commit;<file_sep>/travis.sh # Configuration for SonarCloud #SONAR_TOKEN= # access token from SonarCloud projet creation page -Dsonar.login=XXXX: here it is defined in the environment through the CI SONAR_PROJECT_KEY=sonarcloud_example_cpp-cmake-linux-otherci # project name from SonarCloud projet creation page -Dsonar.projectKey=XXXX SONAR_PROJECT_NAME=sonarcloud_example_cpp-cmake-linux-otherci # project name from SonarCloud projet creation page -Dsonar.projectName=XXXX SONAR_ORGANIZATION=sonarcloud # organization name from SonarCloud projet creation page -Dsonar.organization=ZZZZ # Set default to SONAR_HOST_URL in not provided SONAR_HOST_URL=${SONAR_HOST_URL:-https://sonarcloud.io} mkdir $HOME/.sonar export SONAR_SCANNER_VERSION=4.2.0.1873 export SONAR_SCANNER_HOME=$HOME/.sonar/sonar-scanner-$SONAR_SCANNER_VERSION-linux # download sonar-scanner curl -sSLo $HOME/.sonar/sonar-scanner.zip https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-$SONAR_SCANNER_VERSION-linux.zip > /dev/null 2>&1 unzip -o $HOME/.sonar/sonar-scanner.zip -d $HOME/.sonar/ > /dev/null 2>&1 export PATH=$SONAR_SCANNER_HOME/bin:$PATH export SONAR_SCANNER_OPTS="-server" # download build-wrapper curl -sSLo $HOME/.sonar/build-wrapper-linux-x86.zip https://sonarcloud.io/static/cpp/build-wrapper-linux-x86.zip > /dev/null 2>&1 unzip -o $HOME/.sonar/build-wrapper-linux-x86.zip -d $HOME/.sonar/ > /dev/null 2>&1 export PATH=$HOME/.sonar/build-wrapper-linux-x86:$PATH # Setup the build system cd $HOME git clone https://github.com/microsoft/vcpkg cd vcpkg ./bootstrap-vcpkg.sh ./vcpkg install cpr echo ${TRAVIS_BUILD_DIR} cd ${TRAVIS_BUILD_DIR} ls -a cd Client rm -rf build mkdir build cd build cmake -DCMAKE_TOOLCHAIN_FILE=$HOME/vcpkg/scripts/buildsystems/vcpkg.cmake .. #build inside build wrapper cd .. build-wrapper-linux-x86-64 --out-dir bw-output cmake --build build/ --config Release cd .. ls -a # Run sonar scanner (here, arguments are passed through the command line but most of them can be written in the sonar-project.properties file) sonar-scanner \ -Dsonar.organization=stphn1117 \ -Dsonar.projectKey=<KEY>Got \ -Dsonar.sources=Client,Server/src \ -Dsonar.exclusions=**/nlohmannJson.hpp \ -Dsonar.host.url=https://sonarcloud.io \ -Dsonar.cfamily.build-wrapper-output=Client/bw-output \ -Dsonar.login=$SONARLOGIN <file_sep>/README.md # Got Authors: <NAME> <NAME> <NAME> <NAME> ## Commands Init server | node index.js ## Dependencies: * ### CPR * ### nlohmann json ## Build Client cd Client rm -rf build mkdir build cd build #use you vckpg directory where cpr is placed cmake -DCMAKE_TOOLCHAIN_FILE=/usr/share/vcpkg/scripts/buildsystems/vcpkg.cmake .. cd .. cmake --build build/ --config Release cd .. Client/build/got added .vscode configurations to make it easier to use project in a single folder<file_sep>/Server/src/Sync.js const processChanges = require("./processChanges.js") const oldText = ` La cosa más difícil es conocernos a nosotros mismos; la más fácil es hablar mal de los demás (Tales de Mileto) No puedo enseñar nada a nadie. Solo puedo hacerles pensar (Sócrates) No juzgamos a las personas que amamos (Jean-<NAME>) El conocimiento es poder (<NAME>) El amor inmaduro dice: “te amo porque te necesito”. El maduro dice: “te necesito porque te amo” (<NAME>) `; const newText = ` La cosa más difícil es conocernos a nosotros mismos; la más fácil es hablar mal de los demás (Tales de Mileto) No juzgamos a las personas que amamos (Jean-<NAME>) El amor inmaduro dice: “te amo porque te necesito”. El maduro dice: “te necesito porque te amo” (<NAME>) La peor lucha es la que no se hace (<NAME>) La pobreza no viene por la disminución de las riquezas, sino por la multiplicación de los deseos (Platón) No lastimes a los demás con lo que te causa dolor a ti mismo (Buda) `; let res = processChanges.getDiff("demo", oldText, newText); //let ss = processChanges.applyDiff(oldText,JSON.parse(res)) console.log(res) //console.log(ss)<file_sep>/Server/src/processChanges.js const diff = require("diff"); const oldText = ` La cosa más difícil es conocernos a nosotros mismos; la más fácil es hablar mal de los demás (Tales de Mileto) No puedo enseñar nada a nadie. Solo puedo hacerles pensar (Sócrates) No juzgamos a las personas que amamos (Jean-<NAME>) El conocimiento es poder (<NAME>) El amor inmaduro dice: “te amo porque te necesito”. El maduro dice: “te necesito porque te amo” (<NAME>) `; const newText = ` La cosa más difícil es conocernos a nosotros mismos; la más fácil es hablar mal de los demás (Tales de Mileto) No juzgamos a las personas que amamos (Jean-<NAME>) El amor inmaduro dice: “te amo porque te necesito”. El maduro dice: “te necesito porque te amo” (<NAME>) La peor lucha es la que no se hace (<NAME>) La pobreza no viene por la disminución de las riquezas, sino por la multiplicación de los deseos (Platón) No lastimes a los demás con lo que te causa dolor a ti mismo (Buda) `; const fileName = "src/main.cpp"; let patch = []; patch = getDiff(fileName, oldText, newText); applyDiff(oldText, patch); function getDiff(fileName, oldText, newText){ let patch = diff.createPatch(fileName, oldText, newText); let patchArray = []; patchArray = patch.split("\n"); let structure = []; let array_diff = []; let stringDiff = ""; let n = 0; let line = ""; let newLine = ""; for(let i=5; i < patchArray.length; i++){ if(patchArray[i].startsWith("-")){ line = patchArray[i]; newLine = line.substr(1, line.length); structure.push({ "line": n, "operation": "delete", "content": newLine }); } if(patchArray[i].startsWith("+")){ line = patchArray[i]; newLine = line.substr(1, line.length); structure.push({ "line": n, "operation": "add", "content": newLine }); n++; } else{ if(patchArray[i].startsWith("-")){} else{ structure.push({ "line": n, "operation": "equal", "content": "" }); n++; } } } n = 0; for(let i=5; i < patchArray.length; i++){ if(patchArray[i].startsWith("-")){ line = patchArray[i]; newLine = line.substr(1, line.length); array_diff[n] = newLine; n++; } if(patchArray[i].startsWith("+")){ line = patchArray[i]; newLine = line.substr(1, line.length); array_diff[n] = newLine; n++; } } stringDiff = array_diff.join(); let result = { "stringDiff": stringDiff, "structure": structure } console.log("Result of getDiff()"); console.log(result); return result; } function applyDiff(text, patch){ console.log("\n\nBefore:") console.log(text); myObj = patch; structure = myObj.structure; text_Lines = text.split("\n"); stringResult = ""; for(let i=0; i<structure.length; i++){ if(structure[i].operation === "add"){ insertAt(text_Lines, structure[i].line, structure[i].content); } if(structure[i].operation === "delete"){ for(let j=0; j<text_Lines.length; j++){ if(text_Lines[j] === structure[i].content){ text_Lines.splice(j, 1); } } } } console.log("After:"); for(let i=0; i<text_Lines.length; i++){ stringResult += text_Lines[i] + "\n"; } console.log(stringResult); return stringResult; } function insertAt(array, index, ...elementsArray){ array.splice(index, 0 , ...elementsArray) } /*function getDiff(fileName, oldText, newText){ let jsdiff = diff.createPatch(fileName, oldText, newText); let parsedPatch = diff.parsePatch(jsdiff); return JSON.stringify(parsedPatch); } function applyDiff(text, patch){ let normalPatch = JSON.parse(patch); text = diff.applyPatch(text, normalPatch); return text; }*/ module.exports = { getDiff, applyDiff, insertAt}; <file_sep>/DATABASE.sql DROP DATABASE GOT; CREATE DATABASE GOT; USE GOT; CREATE TABLE IF NOT EXISTS REPOSITORIO ( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, nombre VARCHAR(128) NOT NULL UNIQUE, head VARCHAR(64) ); CREATE TABLE IF NOT EXISTS COMMITS ( -- MD5 HASH id VARCHAR(64) PRIMARY KEY, rep_id INT NOT NULL, FOREIGN KEY (rep_id) REFERENCES REPOSITORIO(id), parent_commit VARCHAR(64), autor VARCHAR(128), mensaje VARCHAR(255) ); CREATE TABLE IF NOT EXISTS ARCHIVO( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, ruta VARCHAR(512) NOT NULL, commit_id VARCHAR(64) NOT NULL, FOREIGN KEY (commit_id) REFERENCES COMMITS(id), huffman_code MEDIUMTEXT, huffman_table MEDIUMTEXT ); -- Tabla de cambios CREATE TABLE IF NOT EXISTS DIFF( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, commit_id VARCHAR(64), FOREIGN KEY (commit_id) REFERENCES COMMITS(id), archivo INT NOT NULL, FOREIGN KEY (archivo) REFERENCES ARCHIVO(id), diff_output TEXT(65535) NOT NULL, md5 varchar(64) ); <file_sep>/Client/CMakeLists.txt cmake_minimum_required(VERSION 3.12) project(got VERSION 1.0.0 LANGUAGES CXX) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) INCLUDE(GNUInstallDirs) set(DEFAULT_BUILD_TYPE "Release") set(INC src/include) set(SOURCE_FILES src/Client.cpp src/Interface.cpp src/main.cpp src/Sync.cpp) set(HEADERS ${INC}/Client.hpp ${INC}/Interface.hpp ${INC}/nlohmannJson.hpp ${INC}/utilities.hpp ${INC}/list.hpp ${INC}/Sync.hpp) add_executable(got ${SOURCE_FILES} ${HEADERS}) find_package(cpr CONFIG REQUIRED) target_link_libraries(got PRIVATE cpr) <file_sep>/Server/src/package.json { "name": "got", "version": "1.0.0", "description": "got server configurations", "main": "index.js", "scripts": { "test": "test" }, "repository": { "type": "git", "url": "https://github.com/stphn1117/Got" }, "author": "<NAME>", "license": "ISC", "dependencies": { "assert": "2.0.0", "diff": "4.0.2", "express": "^4.17.1", "md5": "2.3.0", "mysql2": "^2.1.0", "util": "^0.12.3" }, "devDependencies": { "jsdoc": "^3.6.5" } } <file_sep>/Server/src/DataBase.js const mysql2 = require("mysql2/promise"); const processChanges = require("./processChanges.js") const compressor = require("./Huffman") const util = require("util"); const md5 = require("md5"); const diff = require("diff"); /** * Clase para el manejo de las operaciones de la base de datos */ class DataBase { static instance; static inst = false; mysql; #encoder = null; /** * Representa un objeto de tipo DabaBase * @constructor */ constructor() { if (DataBase.inst) { throw "too many instances" } this.#encoder = new compressor.Huffman(); DataBase.inst = true; this.mysql = { host: 'localhost', user: 'root', password: '<PASSWORD>', database: 'GOT', insecureAuth: true }; } /** * Verifica que se cree un unico objeto de tipo DataBase, define la clase como Singleton */ static Instance() { if (!this.instance) { this.instance = new DataBase(); } return this.instance; } /** * Ejecuta las consultas realizadas a la base de datos * @param {query} query - Solicitud para la base de datos */ async executeQuery(query, printer = false) { const conn = await mysql2.createConnection(this.mysql) const [result] = await conn.execute(query); conn.end(); return result; } /** * Inserta una nueva instancia en la tabla REPOSITORIO con el nombre seleccionado por el usuario * @param {string} name - Nombre del nuevo repositorio */ async insertRepo(name) { const result = await this.executeQuery(`INSERT INTO REPOSITORIO (nombre) VALUES ("${name}")`) return result.insertId; } /** * Inserta una nueva instancia en la tabla COMMITS con sus respectivos atributos * @param {string} id - Identificador del commit * @param {number} repoId - Identificador del repositorio * @param {string} parentCommit - Commit padre * @param {string} mensaje - Mensaje del commit ingresado por el usuario * @param {string} autor - autor del commit */ async insertCommit(id, repoId, parentCommit, mensaje, autor = "") { let sql = `INSERT INTO COMMITS (id, rep_id, parent_commit, mensaje, autor) VALUES ('${id}',${repoId}, '${parentCommit}', '${mensaje}', "${autor}")`; let updateHead = `UPDATE REPOSITORIO SET head = "${id}" WHERE id=${repoId}` this.executeQuery(sql); this.executeQuery(updateHead); return id; } /** * Inserta una nueva instancia en la tabla ARCHIVO con sus respectivos atributos * @param {string} ruta - Ruta del archivo por ingresar en la base de datos * @param {string} commit - Commit del archivo * @param {string} huffman_code - Codigo de Huffman del archivo * @param {string} huffman_table - Tabla de codigos de Huffman de los caracteres en el archivo */ async insertArchivo(ruta, commit, huffman_code, huffman_table) { console.log(commit) let sql = `INSERT INTO ARCHIVO (ruta, commit_id, huffman_code, huffman_table) values ("${ruta}", "${commit}", '${huffman_code}', '${huffman_table}')` return await this.executeQuery(sql); } async insertDiff(commit, ruta, change, newText) { let file = await this.getFile(ruta); let sql = `INSERT INTO DIFF (commit_id, archivo, diff_output, md5) VALUES ("${commit}","${file.id}",'${change}','${md5(newText)}')` return await this.executeQuery(sql); } /** * Obtiene un archivo seleccionado de la tabla ARCHIVO * @param {string} ruta - Ruta del archivo que se busca en la base de datos */ async getFile(ruta) { //console.log("===============================================") let sql = `SELECT * FROM ARCHIVO where ruta="${ruta}"`; let st = await this.executeQuery(sql) //console.log(st) //console.log(st[0]) let [file] = await this.executeQuery(sql); //console.log(file); //console.log("===============================================") return file; } /** * Obtiene los diffs del archivo especifico, y el texto inicial de dicho archivo * @param {string} ruta ruta del archivo en el cliente * @param {string} commit id del commit hasta el cual se quiere recuperar el archivo */ async getFileDiffs(ruta, commit = null) { let file = await this.getFile(ruta); console.log(file) let sql = `SELECT * FROM DIFF WHERE archivo ='${file.id}' ORDER BY id`; let diffs = await this.executeQuery(sql) let contents = ""; //this.#encoder.decompress(file.huffman_code, file.huffman_table) console.log(JSON.parse(file.huffman_table)) let returnVal = { content: contents, changes: [] }; if (!commit) { returnVal.changes = diffs; } else { let toApply = [] let endfor = false; diffs.forEach(element => { if (!endfor) { if (element.commit_id == commit) { endfor = true; } toApply.push(element); } }); returnVal.changes = toApply } return returnVal; } async getFileState(ruta, commit = null) { let rawFile = await this.getFileDiffs(ruta, commit); let finalContent = rawFile.content; //esto debería poder retornar el archivo hasta el estado que se solicita rawFile.changes.forEach((change) => { processChanges.applyDiff(finalContent, JSON.parse(change.diff_output)); }) return finalContent; } async checkFileExists(ruta) { let sql = `SELECT * FROM ARCHIVOS WHERE ruta='${ruta}'` let val = []; val = await this.executeQuery(sql); if (val.length == 0) { console.log("file does not exists") return false; } else { console.log("file exists") return true; } } async checkIfIsLastCommit(commit) { let sql = `SELECT * FROM COMMITS WHERE parent_commit='${commit}'` let val = []; val = await this.executeQuery(sql); if (val.length == 0) { console.log("is last commit") return true; } else { console.log("is not last commit") return false; } } } module.exports.DataBase = DataBase; let a = DataBase.Instance(); //a.checkIfIsLastCommit("123") /*async function test() { let f = await a.getDiffs("test.js") } test() */<file_sep>/Client/src/include/Sync.hpp #include <iostream> #include <fstream> #include <sstream> /** * @brief Clase para la sincronizacion de archivos * */ class Sync{ public: std::string finalContent = ""; std::string buffer = ""; void merge(std::string localFilePath, std::string remoteFile); int askUser(std::string localFilePath); };<file_sep>/Client/src/Client.cpp #include "include/Client.hpp" #include "include/nlohmannJson.hpp" #include <memory> #include <sstream> #include <fstream> #include "include/utilities.hpp" #include "include/Sync.hpp" using json = nlohmann::json; std::shared_ptr<Client> Client::instance = nullptr; std::shared_ptr<Client> Client::getInstance() { if (instance == nullptr) { instance = std::shared_ptr<Client>(new Client()); } return instance; } /** * @brief Obtiene el ultimo commit que se encuentra en el archivo metadata * * @return json Ultimo commit */ json Client::getMetaData() { std::ifstream ifs("./.metadata.json"); json metadata; ifs >> metadata; return metadata; } int Client::overwriteMetaData(json newData){ std::ofstream output; output.open("./.metadata.json"); if (output.is_open()) { output << newData; } output.close(); return 0; } /** * @brief Sirve para el comando got init, envia la informacion de un nuevo repositorio para que este sea inicializado en el servidor * * @param repoName Nombre del nuevo repositorio * @return int Estado de la operacion del cliente */ int Client::init(std::string &repoName) { json req = {{"name", repoName}}; auto res = cpr::Post(cpr::Url{url + "/init"}, jsonHeader, cpr::Body{req.dump()}); json response = json::parse(res.text); if (response["status"].get<std::string>() == "failed") return -1; else return response["id"].get<int>(); } int Client::commit(std::string& message) { json metaData = getMetaData(); json addFiles = metaData["add"]; json changeFiles = metaData["tracked"]; json newFileList; json changedFileList; ce::debuglog("adding files"); for (auto file_route : addFiles) { std::ifstream ifs(file_route.get<std::string>()); std::string content((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>())); json file = {{"route", file_route.get<std::string>()}, {"contents", content}}; newFileList.push_back(file); } ce::debuglog("adding changes to files"); for (auto file_route : changeFiles) { std::ifstream ifs(file_route.get<std::string>()); std::string content((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>())); json file = {{"route", file_route.get<std::string>()}, {"contents", content}}; changedFileList.push_back(file); } ce::debuglog("making the commit json"); json commitJson = {{"repo_id", metaData["id"].get<int>()}, {"message", message}, {"previous_commit", metaData["lastCommitId"].get<std::string>()}, {"add_files", newFileList}, {"changed_files", changedFileList}}; //cpr post auto res = cpr::Post(cpr::Url{url + "/commit"}, jsonHeader, cpr::Body{commitJson.dump()}); json response = json::parse(res.text); for(auto file : addFiles){ changeFiles.push_back(file); } metaData["add"].clear(); metaData["tracked"] = changeFiles; metaData["lastCommitId"] = response["commit_id"].get<std::string>(); overwriteMetaData(metaData); return 0; } int Client::rollback(std::string& route, std::string& commit) { json req = {{"file_route", route}, {"commit_id", commit}}; auto res = cpr::Get(cpr::Url{url + "/rollback"}, jsonHeader, cpr::Body{req.dump()}); json response = json::parse(res.text); json content = response["content"]; std::ofstream output; output.open(route); if (output.is_open()) { output << content; } output.close(); return 0; } int Client::reset(std::string& route) { json req = {{"file_route", route}}; auto res = cpr::Get(cpr::Url{url + "/rollback"}, jsonHeader, cpr::Body{req.dump()}); json response = json::parse(res.text); json content = response["content"]; std::ofstream output; output.open(route); if (output.is_open()) { output << content; } output.close(); return 0; } int Client::sync(std::string& route) { json req = {{"file_route", route}}; auto res = cpr::Get(cpr::Url{url + "/sync"}, jsonHeader, cpr::Body{req.dump()}); json response = json::parse(res.text); json content = response["content"].get<std::string>(); Sync sc; sc.merge(route, content); return 0; } int Client::status(std::string route){ json metadata = getMetaData(); if(route!=""){ std::string id = metadata["lastCommitId"]; json tracked; json req = {{"tracked"},{"commit_id"}}; return 0; }else{ return 0; } }<file_sep>/Client/src/main.cpp #include <iostream> #include "include/Client.hpp" #include "include/Interface.hpp" #include "include/utilities.hpp" #include "include/Sync.hpp" int main(int argc, char *argv[]) { if (argc == 1) { ce::debuglog("no command given"); exit(0); } Interface input; for (int i = 0; i < argc; ++i) { if (i == 4) { ce::log(" \n too many arguments, write help to get more information \n"); } } input.getCommand(argc, argv); return 0; }<file_sep>/demo.cpp void Client::commit(int repo_id, std::string author, std::string messageCommit, json addFiles, json changes){ ->creo commit al server ->for(ruta x in addFiles){ -> abre el archivo -> lee contenido -> llama al rest a agregar archivo (x, contenido del archivo) } ->for(ruta x in changes){ -> abre el archivo -> lee contenido -> llama al rest a diff archivo (x, contenido del archivo) } }<file_sep>/tasks/buildJose.sh cd Client rm -rf build mkdir build cd build cmake -DCMAKE_TOOLCHAIN_FILE=/usr/share/vcpkg/scripts/buildsystems/vcpkg.cmake .. cd .. cmake --build build/ --config Release cd .. Client/build/got<file_sep>/Client/src/Interface.cpp #include <iostream> #include <string.h> #include <memory> #include <fstream> #include <sys/stat.h> #include <dirent.h> #include <string> #include <filesystem> #include "include/utilities.hpp" #include "include/Interface.hpp" #include "include/Client.hpp" #include "include/list.hpp" #include "include/nlohmannJson.hpp" //Tareas comprobar lo de json files //agreagar directorios raiz namespace fs = std::filesystem; json metadata; json TrackFiles(json filesToTrack); /** * @brief Obtiene el comando ejecutado por el cliente y llama a las respectivas funciones relacionadas * * @param count * @param command Comando ingresado por el usuario */ void Interface::getCommand(int count, char **command) { if (strcmp(command[1], "help") == 0) { ce::log("instructions:\n\n"); ce::log("init <name> : ", "intilialize a repository on the remote server\n\n"); ce::log("add [-A] [name] : ", "add a file to the tracked list on next commit\n\n"); ce::log("commit <message>: ", "send performed changes to server\n\n"); ce::log("reset <file> :" ,"return file to the last commit\n\n"); ce::log("sync<file> :" ,"syncronize server and local versions \n\n"); ce::log("status <file> :" ,"check for new files, changes and deletions \n\n"); } else if (strcmp(command[1], "init") == 0) { std::string repoName(command[2]); int id = Client::getInstance()->init(repoName); createProject(count, command, id); } else if (strcmp(command[1], "Add") == 0) { handleAddFile(command); } else if (strcmp(command[1], "commit") == 0) { std::string message(command[2]); Client::getInstance()->commit(message); } else if (strcmp(command[1], "rollback") == 0) { std::string filex(command[2]); std::string commit(command[3]); Client::getInstance()->rollback(filex,commit); } else if (strcmp(command[1], "reset") == 0) { std::string filex(command[2]); Client::getInstance()->reset(filex); } else if (strcmp(command[1], "sync") == 0) { std::string filex(command[2]); Client::getInstance()->sync(filex); } else { ce::debuglog("the command isn't correct, execute help command"); } } /** * @brief Recolecta los archivos de un directorio especifico * * @param filesToTrack json que contiene los archivos de seguimiento * @return json conjunto de archivos */ json TrackFiles(json filesToTrack) { std::string path = "./"; for (const auto &entry : fs::recursive_directory_iterator(path)) filesToTrack.push_back(entry.path()); return filesToTrack; } /** * @brief Inicializa un nuevo repositorio en el cliente, crea el archivo .gotignore y el archivo que contiene la metadata del proyecto en Got * * @param count * @param command Nombre del repositorio * @param id Identificador del repositorio */ void Interface::createProject(int count, char **command, int id) { //create .gotignore std::ofstream file; std::string gotIgnore = "./.gotignore"; file.open(gotIgnore); file << "gotignore files"; file.close(); ce::log("gotignore created"); //create metadata json std::ofstream metadataFile; std::string metaPath = "./.metadata.json"; metadataFile.open(metaPath); //update metadata std::string files; DIR *dp; struct dirent *ep; dp = opendir("./"); nlohmann::json filesTrack; metadata["id"] = id; metadata["lastCommitId"] = "nocommit"; metadata["repoName"] = command[2]; metadata["tracked"] = json::array(); metadata["add"] = TrackFiles(filesTrack); metadataFile << metadata; metadataFile.close(); ce::log(" new project created"); } /** * @brief Maneja la funcion de agregar archivos al proyecto * * @param command Comando ingresado por el usuario */ void Interface::handleAddFile(char **command) { FILE *file; if (strcmp(command[2], "All") == 0) { filesAdded.push_back(TrackFiles(filesAdded)); ce::log(filesAdded); } else { if (file = fopen(command[2], "r")) { fclose(file); Interface::filesAdded.push_back(command[2]); ce::log("file added"); } else { ce::log("file doesn't exist"); } } } <file_sep>/Client/src/Sync.cpp #include "include/Sync.hpp" #include "include/utilities.hpp" /** * @brief Realiza la comparacion y combinacion de archivos de forma interactiva * * @param localFilePath Ubicacion del archivo local * @param remoteFileString Archivo remoto en forma de string */ void Sync::merge(std::string localFilePath, std::string remoteFileString) { std::ifstream localFile(localFilePath); std::istringstream remoteFile(remoteFileString); std::string localLine; std::string remoteLine; int mergeAction; int lines = 0; int localFileLineCount = 0; int remoteFileLineCount = 0; while (getline(localFile, localLine)) { localFileLineCount++; }; while (getline(remoteFile, remoteLine)) { remoteFileLineCount++; }; localFile.clear(); localFile.seekg(0); remoteFile.clear(); remoteFile.seekg(0); int cnt = 0; while (getline(localFile, localLine) && getline(remoteFile, remoteLine)) { cnt++; if (localLine == remoteLine) { finalContent += localLine + "\n"; } else { ce::log("_______/ Versiones /_______ ", "\nLocal: " + localLine, "\nRemota: " + remoteLine); mergeAction = askUser(localFilePath); if (mergeAction == 1) { //Conservar local finalContent += localLine + "\n"; } else if (mergeAction == 2) { //Reemplazar local por remoto finalContent += remoteLine + "\n"; } else if (mergeAction == 3) { //Reemplazar local por remoto y guardar local finalContent += remoteLine + "\n"; buffer += localLine + " >>>>>>> saved from line[" + std::to_string(cnt) + "]==\n"; } } lines++; } localFile.clear(); localFile.seekg(0); remoteFile.clear(); remoteFile.seekg(0); if (localFileLineCount > lines) { ce::log("Desea agregar el contenido restante del archivo local?\n1. Si\n2. No"); std::cin >> mergeAction; if (mergeAction == 1) { for (int line = 0; getline(localFile, localLine); line++) { if (line >= lines && line < localFileLineCount) { finalContent += localLine + "\n"; } } } } else if (remoteFileLineCount > lines) { ce::log("\n¿Desea agregar el contenido restante del archivo remoto?\n1. Si\n2. No"); std::cin >> mergeAction; if (mergeAction == 1) { for (int line = 0; getline(remoteFile, remoteLine); line++) { if (line >= lines && line < remoteFileLineCount) { finalContent += remoteLine + "\n"; } } } } //ce::log(finalContent); //ce::log(buffer); if(buffer !=""){ finalContent += "[=== cambios locales guardados ====]\n"; } std::ofstream output; output.open(localFilePath); if (output.is_open()) { output << (finalContent + buffer); } output.close(); } /** * @brief Permite al usuario seleccionar una forma de combinar los archivos * * @param localFilePath Ubicacion del archivo local * @return int Representacion de la modalidad de merge seleccionada */ int Sync::askUser(std::string localFilePath) { int mergeAction; ce::log("\nSeleccione una de las siguientes opciones para el merge del archivo ", localFilePath); ce::log("1. Conservar local\n2. Reemplazar local por remoto\n3. Reemplazar local por remoto y guardar local"); std::cin >> mergeAction; return mergeAction; } <file_sep>/Client/src/include/Client.hpp #ifndef CLIENT_H #define CLIENT_H #include "nlohmannJson.hpp" #include <iostream> #include <ostream> #include <memory> #include <cpr/cpr.h> using json = nlohmann::json; class Client{ private: const cpr::Header jsonHeader; std::string url = "http://localhost:3000"; static std::shared_ptr<Client> instance; Client():jsonHeader{cpr::Header{{"Content-Type", "application/json"}}}{}; json getMetaData(); int overwriteMetaData(json newData); public: static std::shared_ptr<Client> getInstance(); int init(std::string& repo_name); void get(int files[], std::string specifyCommit, int Time); int commit(std::string& message); int rollback(std::string& route, std::string& commit); int reset(std::string& route); int sync(std::string& route); int status(std::string route=""); }; #endif
0c357afbbab0d23e8db4f399246098a2216e090b
[ "SQL", "JSON", "CMake", "JavaScript", "Markdown", "C++", "Shell" ]
21
C++
stphnVi/Got
ff88f42fc44e2849893dd1d78781aad3c0723d48
e1b7f90dcb6189f5ee61181aff9cadf06e44453a
refs/heads/master
<repo_name>phkakaka/Curiosity_1619_4.01<file_sep>/Curiosity_1619.X/SourceFiles/COS/COS_Defs.h /** @file COS_Defs.h * @ingroup group_COS_NutsBolts * * @author <NAME> * @author <NAME> * * */ #ifndef COS_DEFS #define COS_DEFS /******************************************************************************/ /****************************** DECLARATIONS **********************************/ /******************************************************************************/ /* Misc or general purpose constant definitions for all ETM tasks. */ #define TRUE 1 #define FALSE 0 #define BYTE 8 #define BYTE_MSB 0x80 #define BYTE_LSB 0x01 /* Status Defines */ #define ON 1 #define OFF 0 #define HIGH 1 #define LOW 0 #define UINT_16_MAX 65535 #define UINT_16_MIN 0 #define SINT_16_MAX 32767 #define SINT_16_MIN -32768 #define UINT_8_MAX 255 #define UINT_8_MIN 0 #define SINT_8_MAX 127 #define SINT_8_MIN -128 #define BIN0CONV 1 /* bin point 0 conversion factor */ #define BIN1CONV 2 /* bin point 1 conversion factor */ #define BIN2CONV 4 /* bin point 2 conversion factor */ #define BIN3CONV 8 /* bin point 3 conversion factor */ #define BIN4CONV 16 /* bin point 4 conversion factor */ #define BIN5CONV 32 /* bin point 5 conversion factor */ #define BIN6CONV 64 /* bin point 6 conversion factor */ #define BIN7CONV 128 /* bin point 7 conversion factor */ #define BIN8CONV 256 /* bin point 8 conversion factor */ #define BIN9CONV 512 /* bin point 9 conversion factor */ #define BIN10CONV 1024 /* bin point 10 conversion factor */ #define BIN11CONV 2058 /* bin point 11 conversion factor */ #define BIN12CONV 4096 /* bin point 12 conversion factor */ #define BIN13CONV 8192 /* bin point 13 conversion factor */ #define BIN14CONV 16384 /* bin point 14 conversion factor */ #define BIN15CONV 32768 /* bin point 15 conversion factor */ #define BIN16CONV 65536 /* bin point 16 conversion factor */ /* COS Variable Types */ typedef unsigned char UINT_1; /* unsigned integer 8 bit value */ typedef unsigned char UINT_8; /* unsigned integer 8 bit value */ typedef signed char SINT_8; /* signed integer 8 bit value */ typedef unsigned short UINT_16; /* unsigned integer 16 bit value */ typedef signed short SINT_16; /* signed integer 16 bit value */ typedef unsigned long UINT_32; /* unsigned integer 32 bit value */ typedef signed long SINT_32; /* signed integer 32 bit value */ typedef float FLOAT_24; /* floating point 24 bit value */ typedef double FLOAT_32; /* floating point 32 bit value */ #define MS_PER_SEC 1000 /* number of milliseconds in a second */ #define SECS_PER_MIN 60 /* number of seconds in a minute */ #define TIME_10_SECS 10000 /* number of milliseconds in ten seconds */ #define TIME_5_SECS 5000 /* number of milliseconds in five seconds */ #define TIME_4_SECS 4000 /* number of milliseconds in four seconds */ #define TIME_2_SECS 2000 /* number of milliseconds in two seconds */ #define TIME_ONE_SEC 1000 /* number of milliseconds in 1 second */ #define TIME_HALF_SEC 500 /* number of milliseconds in 1/2 second */ #define TIME_50_MSEC 50 /* number of milliseconds in 50 milliseconds */ #define TIME_100_MSEC 100 /* number of milliseconds in 100 milliseconds */ #define STATIC static #define COS_FORCE_WDT_RESET() while(1) #endif<file_sep>/Curiosity_1619.X/SourceFiles/SunSensor/SHT25.c /** @file Led.c * @ingroup SunSensor * * @author <NAME> * * */ /*-- Includes --*/ #include "../../mcc_generated_files/mcc.h" #include "SHT25.h" #include "UART_Display.h" #include "I2C_Driver.h" #include "../../mcc_generated_files/examples/i2c_master_example.h" #include "stdlib.h" #define SHT31_ADDR_W 0x44 // sensor I2C address + write bit #define SHT31_ADDR_R 0x45 // sensor I2C address + read bit #define Numtoasc(b) ('0'+ b) //Variables with external linkage UINT_16 SensirionTemperature_UBP8; UINT_16 SensirionRH_UBP8; float SensirionTemperature_float; float SensirionRH_float; UINT_1 SHT25_Fault; UINT_8 ErrorStat; UINT_16 I2C_Timer; //Variables used only by this module UINT_8 checksum; UINT_8 TemperatureRaw_H; UINT_8 TemperatureRaw_L; UINT_16 TemperatureRaw; UINT_8 RelativeHumidityRaw_H; UINT_8 RelativeHumidityRaw_L; UINT_16 RelativeHumidityRaw; SHT25_State_tt SHT25_State = SHT25_MEASURE_INIT; UINT_8 Command[2] = {0x22,0x20}; UINT_8 RxBuff[8]; UINT_8 AddressW = SHT25_ADDR_W; UINT_16 TimerCounter = 0; static UINT_8 IsMeasureDone = FALSE; void SHT25_StateMachine(void) { switch(SHT25_State) { case SHT25_MEASURE_INIT: SHT25_State = SHT25_MEASURE_TEMP_0; break; case SHT25_MEASURE_TEMP_0: I2C_WriteNBytes(SHT31_ADDR_W,Command,2); SHT25_State = SHT25_MEASURE_TEMP_WAIT; TimerCounter = 0; break; case SHT25_MEASURE_TEMP_WAIT: TimerCounter++; if (TimerCounter > 50) { Command[0] = 0xE0; Command[1] = 0x00; I2C_WriteNBytes(SHT31_ADDR_W,Command,2); TimerCounter = 0; SHT25_State = SHT25_MEASURE_TEMP_1; } break; case SHT25_MEASURE_TEMP_1: I2C_ReadNBytes(SHT31_ADDR_W,RxBuff,6); TemperatureRaw_H = RxBuff[0]; TemperatureRaw_L = RxBuff[1]; TemperatureRaw = ((UINT_16)(TemperatureRaw_H) << 8) + TemperatureRaw_L ; RelativeHumidityRaw_H = RxBuff[3]; RelativeHumidityRaw_L = RxBuff[4]; RelativeHumidityRaw = ((UINT_16)(RelativeHumidityRaw_H) << 8) + RelativeHumidityRaw_L ; SHT25_State = SHT25_CALC_TEMP_0; break; case SHT25_CALC_TEMP_0: SensirionTemperature_float = SHT3x_CalcTemperatureC_F(); SensirionRH_float = SHT3x_CalcRelativeHumidity_F(); //SensirionTemperature_float = SHT3x_CalcTemperatureC(); //SensirionRH_float = SHT3x_CalcRelativeHumidity(); SHT25_State = SHT25_CALC_RH_0; IsMeasureDone = TRUE; break; case SHT25_CALC_RH_0: SHT25_State = SHT25_MEASURE_TEMP_WAIT; break; default: break; } } void SHT25_FaultHand(void) { TemperatureRaw = 0; RelativeHumidityRaw = 0; SHT25_Fault = 1; SHT25_State = SHT25_CALC_TEMP_0; } float SHT3x_CalcTemperatureC_F(void) { float TemperatureFloat; TemperatureFloat = (float)TemperatureRaw * 175 / 65535 - 45; return TemperatureFloat ; } float SHT3x_CalcRelativeHumidity_F(void) { float RelativeHumidityFloat; RelativeHumidityFloat = (float)RelativeHumidityRaw * 100 / 65535; return RelativeHumidityFloat ; } float GetTemperatureC_F(void) { return SensirionTemperature_float; } float GetRelativeHumidity_F(void) { return SensirionRH_float; } UINT_8 IsSHT31MeasureDone(void) { return IsMeasureDone; } UINT_16 SHT3x_CalcTemperatureC(void) { SINT_32 TemperatureTemp; UINT_16 Temperature_UBP8; UINT_16 Temperature_U16; UINT_8 Temperature_L8; TemperatureTemp = (UINT_32)TemperatureRaw * 175; Temperature_U16 = (UINT_16)(TemperatureTemp >> 16); Temperature_UBP8 = (UINT_16)Temperature_U16 - 45; return Temperature_UBP8 ; } UINT_16 SHT3x_CalcRelativeHumidity(void) { SINT_32 RelativeHumidityTemp; UINT_16 RelativeHumidity_UBP8; UINT_8 RelativeHumidity_U16; UINT_8 RelativeHumidity_L8; RelativeHumidityTemp = (UINT_32)RelativeHumidityRaw * 100; RelativeHumidity_U16 = (UINT_16)(RelativeHumidityTemp >> 16); RelativeHumidity_UBP8 = (UINT_16)RelativeHumidity_U16; return RelativeHumidity_UBP8 ; } <file_sep>/Curiosity_1619.X/SourceFiles/SunSensor/UART_Display.c /** @file Led.c * @ingroup SunSensor * * @author <NAME> * * */ /*-- Includes --*/ #include "../../mcc_generated_files/mcc.h" #include "UART_Display.h" #include "AD.h" #include "SHT25.h" #include "stdlib.h" static uint8_t U8Message = 0x55; static uint8_t NewMessageFlag; static uint8_t counter; UART_tt UART_STATE = UART_TEMP; static uint8_t TimerCounter; void SendByUart(uint8_t Txt) { U8Message = Txt; NewMessageFlag = 1; } void UartDisplay(void) { float TempF; float HumiF; float NtcTempF; UINT_16 Temp; UINT_16 Humi; UINT_16 NtcTemp; UINT_8 str[8]; switch (UART_STATE) { case UART_TEMP: if (IsSHT31MeasureDone()) { EUSART_Write('T'); TempF = GetTemperatureC_F(); Temp = (UINT_16)(TempF * 100); if (TempF < 0) { EUSART_Write('-'); TempF = abs(TempF); } //sprintf(str, "%2.2f" , Temp); sprintf(str, "%4d" , Temp); EUSART_Write(str[0]); EUSART_Write(str[1]); EUSART_Write('.'); EUSART_Write(str[2]); EUSART_Write(str[3]); EUSART_Write(' '); } UART_STATE = UATR_HUMI; break; case UATR_HUMI: if (IsSHT31MeasureDone()) { EUSART_Write('H'); HumiF = GetRelativeHumidity_F(); Humi = (UINT_16)(HumiF * 100); //sprintf(str, "%2.2f" , Humi); sprintf(str, "%4d" , Humi); EUSART_Write(str[0]); EUSART_Write(str[1]); EUSART_Write('.'); EUSART_Write(str[2]); EUSART_Write(str[3]); EUSART_Write(' '); } UART_STATE = UART_NTC; break; case UART_NTC: if (IsADMeasureDone()) { EUSART_Write('N'); NtcTempF = GetNtcTemp(); NtcTemp = (UINT_16)(NtcTempF * 100); if (NtcTempF < 0) { EUSART_Write('-'); NtcTemp = abs(NtcTemp); } //sprintf(str, "%2.2f" , NtcTemp); sprintf(str, "%4d" , NtcTemp); EUSART_Write(str[0]); EUSART_Write(str[1]); EUSART_Write('.'); EUSART_Write(str[2]); EUSART_Write(str[3]); EUSART_Write(' '); } UART_STATE = UART_Refresh_Interval; break; case UART_Refresh_Interval: TimerCounter++; if (TimerCounter > 50) { TimerCounter = 0; UART_STATE = UART_TEMP; } break; default: break; } } <file_sep>/Curiosity_1619.X/SourceFiles/COS/GlobalDef.h /** @file GlobalDef.h * @ingroup group_COS_Setup * * @author <NAME> * @author <NAME> * * */ #ifndef GLOBALDEF_H #define GLOBALDEF_H /* This module is used for global defines and should be included by every module */ #ifndef _UNIT_TESTING_ #include <xc.h> #include "COS_Defs.h" #else #include "Unit_Test_Helper.h" #endif // ifndef _UNIT_TESTING_ #include "COS_UserSetup.h" #include "COS_Main.h" #endif /* GLOBALDEF_H */ <file_sep>/Curiosity_1619.X/nbproject/Makefile-variables.mk # # Generated - do not edit! # # NOCDDL # CND_BASEDIR=`pwd` # default configuration CND_ARTIFACT_DIR_default=dist/default/production CND_ARTIFACT_NAME_default=Curiosity_1619.X.production.hex CND_ARTIFACT_PATH_default=dist/default/production/Curiosity_1619.X.production.hex CND_PACKAGE_DIR_default=${CND_DISTDIR}/default/package CND_PACKAGE_NAME_default=curiosity1619.x.tar CND_PACKAGE_PATH_default=${CND_DISTDIR}/default/package/curiosity1619.x.tar <file_sep>/Curiosity_1619.X/SourceFiles/COS/COS_Main.c /** @file COS_Main.c * @ingroup group_COS_NutsBolts * * @author <NAME> * @author <NAME> * * */ #include "GlobalDef.h" /* Variable definitions for the task manager. */ UINT_8 COS_tsk_ind; /**< Task index for current task */ UINT_8 COS_tsk_msk; /**< Task mask for current time slot */ UINT_8 COS_tsk_ena; /**< Task enable flag */ /* Variable definitions for the timer handler. */ UINT_16 COS_ms_tmr; /**< Task manager ms timer */ volatile UINT_16 COS_sec_tmr; /**< second timer */ UINT_16 COS_tsk_tmr; /**< task slot timer */ UINT_16 COS_tcnt_val; /**< value of GPT TCNT register */ UINT_16 COS_tcnt_lst; /**< GPT TCNT at last ms interval */ /** * @brief Function called to initialize the COS scheduler * * This function initializes the COS scheduler and should be called near the end * of microprocessor initialization before entering the main while loop. * * @ingroup group_COS_Setup */ void COS_Init(void) { UINT_8 tempbyte1, tempbyte2; COS_TimerSetup(); #ifdef DEBUG_COS_TSK_TIMES DebugTaskTimerInit(); #endif COS_tsk_ind = 0; COS_tsk_msk = COS_SLOT_1; COS_tsk_ena = TRUE; COS_ms_tmr = 0; COS_sec_tmr = 0; COS_tsk_tmr = 0; tempbyte2 = TMR1H; tempbyte1 = TMR1L; if (tempbyte2 != TMR1H) { tempbyte2 = TMR1H; tempbyte1 = TMR1L; } COS_tcnt_val = ((UINT_16)tempbyte2 << 8)&0xff00; COS_tcnt_val = COS_tcnt_val | ((UINT_16)tempbyte1 & 0x00ff); COS_tcnt_lst = COS_tcnt_val; } /** * @brief This function initializes Timer 1 for use by the COS Scheduler. * * This function is automatically called from COS_Init(). It initializes * Timer 1 at 0 ticks and applies the COS_TMR1_CON configuration. * * @ingroup group_COS_NutsBolts */ void COS_TimerSetup(void) { /* Timer 1 used for Base System Tick Time */ /* Timer 1 Register pair must be cleared before enabling interrupts */ TMR1H = 0; TMR1L = 0; /* Timer 1 Clock Source Fosc/4 = 4MHz */ /* Set Timer 1 Prescaler to 1:4 --> Timer1Tick = 1usec */ /* Switch On Timer 1 */ T1CON = COS_TMR1_CON; } /** * @brief This function polls Timer 1 and flags when tasks slots should run. * * This function must be called in the main function. It works on a polling basis * monitoring Timer 1 for a 1ms tick. This allows for jitter and does not force * the microprocessor into an ISR continuously. After 1ms passes, this function checks * if a slot needs to run and sets a flag accordingly. If LIN is enabled, diagnostics * are called from here to ensure they are updated every 1ms. * * @ingroup group_COS_Setup */ void COS_TmrHandler(void) { UINT_8 tempbyte1, tempbyte2; tempbyte2 = TMR1H; tempbyte1 = TMR1L; if (tempbyte2 != TMR1H) { tempbyte2 = TMR1H; tempbyte1 = TMR1L; } COS_tcnt_val = (UINT_16) (tempbyte2 << 8)&0xff00; COS_tcnt_val = COS_tcnt_val | (UINT_16) (tempbyte1 & 0x00ff); if (((UINT_16) ((UINT_16) COS_tcnt_val - (UINT_16) COS_tcnt_lst) >= (UINT_16) TIMER1_COUNTS_PER_MS)) { COS_tcnt_lst = COS_tcnt_lst + TIMER1_COUNTS_PER_MS; COS_ms_tmr++; if (COS_ms_tmr >= MS_PER_SEC) { COS_ms_tmr = 0; COS_sec_tmr++; } COS_tsk_tmr++; if ((COS_tsk_tmr >= COS_TSK_SLT) && (!COS_tsk_ena)) { COS_tsk_tmr = 0; COS_tsk_ena = TRUE; } } } /** * @brief This function calls tasks from the task list as needed. * * The Task Manager will call the appropriate tasks for the current slot. * This function should be called from within the main while loop only if * COS_tsk_ena is true. * * @ingroup group_COS_Setup */ void COS_TskMan(void) { if ((COS_tsk[COS_tsk_ind].sched & COS_tsk_msk) != 0) { #ifdef DEBUG_COS_TSK_TIMES DEBUG_TASKTIMER_REGISTER = 0; DEBUG_TASKTIMER_IF_FLAG = 0; DEBUG_TASKTIMER_TMR_ON = 1; #endif (*COS_tsk[COS_tsk_ind].tptr)(); #ifdef DEBUG_COS_TSK_TIMES DEBUG_TASKTIMER_TMR_ON = 0; DEBUG_TASKTIMER_REGISTER = 0; #endif } COS_tsk_ind++; if (COS_tsk_ind >= NUM_TSKS) { COS_tsk_ena = FALSE; COS_tsk_ind = 0; /* Check for valid task mask and reset accordingly if not valid */ if (!((COS_tsk_msk == COS_SLOT_1) || (COS_tsk_msk == COS_SLOT_2) || (COS_tsk_msk == COS_SLOT_3) || (COS_tsk_msk == COS_SLOT_4) || (COS_tsk_msk == COS_SLOT_5) || (COS_tsk_msk == COS_SLOT_6) || (COS_tsk_msk == COS_SLOT_7) || (COS_tsk_msk == COS_SLOT_8))) { #ifdef _COS_TSKMSK_SOFT_RST COS_tsk_msk = COS_SLOT_8; /* Shift will set to first slot */ #else /* _COS_TSKMSK_HARD_RST */ COS_FORCE_WDT_RESET(); #endif } /* Move on to next task slot */ COS_tsk_msk = COS_tsk_msk >> 1; if (COS_tsk_msk == 0x00) { COS_tsk_msk = COS_SLOT_1; } } } #ifdef DEBUG_COS_TSK_TIMES /** * @brief This function initializes Timer X for debug use by the COS Scheduler. * * This function is automatically called from COS_Init(). It initializes * Timer X at 0 ticks and sets it up for 1ms overflow to track whether tasks are * exceeding their 1ms task slot. The user can then enable interrupts to trap * the uC if a task exceeds 1ms. * * @ingroup group_COS_NutsBolts */ void DebugTaskTimerInit(void) { DEBUG_TASKTIMER_CONFIG_REG = DEBUG_TASKTIMER_CONFIG; DEBUG_TASKTIMER_TMR_ON = 0; DEBUG_TASKTIMER_REGISTER = 0; DEBUG_TASKTIMER_PR_REGISTER = DEBUG_TASKTIMER_PR_VALUE; DEBUG_TASKTIMER_IF_FLAG = 0; #ifdef DEBUG_TASKTIMER_INT_ENABLE DEBUG_TASKTIMER_IE_FLAG = 1; #endif } #endif <file_sep>/Curiosity_1619.X/SourceFiles/SunSensor/I2C_Driver.h #ifndef __IIC_DRIVER_ #define __IIC_DRIVER_ #include "../COS/GlobalDef.h" #define HIGH 1 #define LOW 0 #define ACK_ERROR 1 #define TIME_OUT_ERROR 2 #define CHECKSUM_ERROR 4 #define ACK 0 #define NO_ACK 1 extern void I2C_Init(void); extern void I2C_StartCondition(void); extern void I2C_StopCondition(void); extern void I2C_MasterSendAck(void); extern void I2C_MasterSendNack(void); extern UINT_8 I2C_WriteByte (UINT_8 txByte); extern UINT_8 I2C_ReadByte (UINT_8 ack); extern void I2C_Init_IO(void); extern void I2C_StartCondition_IO(void); extern UINT_8 I2C_WriteByte_IO (UINT_8 txByte); #endif <file_sep>/Curiosity_1619.X/SourceFiles/COS/COS_UserSetup.h /** @file COS_UserSetup.h * @ingroup group_COS_Setup * * @author <NAME> * @author <NAME> * * */ /* Include GlobalDef.h in all C files */ #ifndef COS_USERSETUP #define COS_USERSETUP #ifndef _UNIT_TESTING_ #include "COS_Defs.h" #else #include "Unit_Test_Helper.h" #endif //////////////////////////////////////////////////////////////////////////////// /////////////////////////// Start User Setup /////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /*********** FOSC Definition ***********/ #define _XTAL_FREQ 16000000 /* Define FOSC in Hz */ /*********** LIN Configuration ***********/ #define _COS_LIN_ENABLED /* Set to define if LIN is used */ #ifdef _COS_LIN_ENABLED #define CS_PIN LATCbits.LATC1 /* Define CS Pin for LIN transceiver */ #endif // _COS_LIN_ENABLED /******** Timer Setup - Provide Timer1 with tick scheme to generate 1ms *******/ #define COS_TMR1_CON 0b00100001 /* Set for 1usec tick */ #define TIMER1_COUNTS_PER_MS 1000 /**************** Invalid Task Mask Behavior - ONLY SELECT ONE ****************/ #undef _COS_TSKMSK_SOFT_RST /* Recover by going to first task slot */ #define _COS_TSKMSK_HARD_RST /* Recover by forcing watchdog reset */ /******* Debug Setup - Provide TxCON such that TimerX interrupts in 1ms *******/ /* Example: * 32MHz FOSC -> 8MHz base freq. * Need 1ms interrupt = 1:64 prescaler, 1:1 postscaler 125 ticks * Set Timer OFF (automatically turned on in the scheduler at correct time) */ #undef DEBUG_COS_TSK_TIMES #ifdef DEBUG_COS_TSK_TIMES // Select only one timer #undef DEBUG_TASKTIMER_SELECT_TIMER2 #undef DEBUG_TASKTIMER_SELECT_TIMER4 #undef DEBUG_TASKTIMER_SELECT_TIMER6 // Set up timer for 1ms interrupt // Use DEBUG_TASKTIMER_IF_FLAG for reading the interrupt flag in your ISR #define DEBUG_TASKTIMER_CONFIG 0bxxxxxxxx #define DEBUG_TASKTIMER_PR_VALUE xxx #undef DEBUG_TASKTIMER_INT_ENABLE #endif //////////////////////////////////////////////////////////////////////////////// //////////////////////////// End User Setup //////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// ///* Example main function */ ///* ///* void main() ///* { ///* CLRWDT(); ///* ///* MIC_Initializations(); /* All Initializations are done inside this function */ ///* COS_Init(); ///* ///* CLRWDT(); ///* ///* while (1) ///* { ///* COS_TmrHandler(); ///* l_cyclic_com_task(); /* Refresh LIN Buffers */ ///* if (COS_tsk_ena) ///* { ///* COS_TskMan(); ///* } ///* l_cyclic_com_task(); /* Refresh LIN Buffers */ ///* } ///* } */ #ifdef DEBUG_COS_TSK_TIMES #ifdef DEBUG_TASKTIMER_SELECT_TIMER2 #define DEBUG_TASKTIMER_CONFIG_REG T2CON #define DEBUG_TASKTIMER_TMR_ON T2CONbits.TMR2ON #define DEBUG_TASKTIMER_REGISTER TMR2 #define DEBUG_TASKTIMER_PR_REGISTER PR2 #define DEBUG_TASKTIMER_IF_FLAG PIR1bits.TMR2IF #define DEBUG_TASKTIMER_IE_FLAG PIE1bits.TMR2IE #elif defined DEBUG_TASKTIMER_SELECT_TIMER4 #define DEBUG_TASKTIMER_CONFIG_REG T4CON #define DEBUG_TASKTIMER_TMR_ON T4CONbits.TMR4ON #define DEBUG_TASKTIMER_REGISTER TMR4 #define DEBUG_TASKTIMER_PR_REGISTER PR4 #define DEBUG_TASKTIMER_IF_FLAG PIR3bits.TMR4IF #define DEBUG_TASKTIMER_IE_FLAG PIE3bits.TMR4IE #elif defined DEBUG_TASKTIMER_SELECT_TIMER6 #define DEBUG_TASKTIMER_CONFIG_REG T6CON #define DEBUG_TASKTIMER_TMR_ON T6CONbits.TMR6ON #define DEBUG_TASKTIMER_REGISTER TMR6 #define DEBUG_TASKTIMER_PR_REGISTER PR6 #define DEBUG_TASKTIMER_IF_FLAG PIR3bits.TMR6IF #define DEBUG_TASKTIMER_IE_FLAG PIE3bits.TMR6IE #endif // DEBUG_TIMER_SELECT_TIMER6 #endif // DEBUG_COS_TSK_TIMES #ifdef _UNIT_TESTING_ #undef _COS_LIN_ENABLED // Workaround for LIN in Unit Testing #endif // _UNIT_TESTING_ #endif<file_sep>/Curiosity_1619.X/SourceFiles/SunSensor/SHT25.h /** @file Led.c * @ingroup SunSensor * * @author <NAME> * * */ #ifndef _SHT25_H_ #define _SHT25_H_ /*-- Includes --*/ #include "../COS/COS_Defs.h" typedef enum { SHT25_MEASURE_INIT, //Init Hardware SHT25_MEASURE_TEMP_0, // trigger humidity sensor temperature measurement SHT25_MEASURE_TEMP_1, // poll for measurement complete and read temperature SHT25_MEASURE_TEMP_WAIT, SHT25_MEASURE_RH_0, // trigger relative humidity measurement SHT25_MEASURE_RH_1, // poll for measurement complete and read relative humidity SHT25_CALC_TEMP_0, // calculate temperature in degrees C bin 8 SHT25_CALC_RH_0, // calculate temperature in relative humidity nim 8 } SHT25_State_tt; #define I2C_MEASUREMENT_TIME_OUT 200 #define I2C_TASK_TIME TIME_TSK_EVERYSLOT // sensor command #define TRIG_T_MEASUREMENT_HM 0xE3 // command trig. temp meas. hold master #define TRIG_RH_MEASUREMENT_HM 0xE5 // command trig. humidity meas. hold master #define TRIG_T_MEASUREMENT_POLL 0xF3 // command trig. temp meas. no hold master #define TRIG_RH_MEASUREMENT_POLL 0xF5 // command trig. humidity meas. no hold master #define USER_REG_W 0xE6 // command writing user register #define USER_REG_R 0xE7 // command reading user register #define SOFT_RESET 0xFE // command soft reset #define SHT2x_RES_12_14BIT 0x00 // RH=12bit, T=14bit #define SHT2x_RES_8_12BIT 0x01 // RH= 8bit, T=12bit #define SHT2x_RES_10_13BIT 0x80 // RH=10bit, T=13bit #define SHT2x_RES_11_11BIT 0x81 // RH=11bit, T=11bit #define SHT2x_RES_MASK 0x81 // Mask for res. bits (7,0) in user reg. #define SHT2x_EOB_ON 0x40 // end of battery #define SHT2x_EOB_MASK 0x40 // Mask for EOB bit(6) in user reg. #define SHT2x_HEATER_ON 0x04 // heater on #define SHT2x_HEATER_OFF 0x00 // heater off #define SHT2x_HEATER_MASK 0x04 // Mask for Heater bit(2) in user reg. // measurement signal selection #define HUMIDITY 0 #define TEMP 1 #define SHT25_ADDR_W 128 // sensor I2C address + write bit #define SHT25_ADDR_R 129 // sensor I2C address + read bit extern void SHT25_StateMachine(void); extern void SHT25_FaultHand(void); extern UINT_16 SHT2x_CalcTemperatureC(void); extern UINT_16 SHT2x_CalcRelativeHumidity(void); extern UINT_16 SHT3x_CalcTemperatureC(void); extern UINT_16 SHT3x_CalcRelativeHumidity(void); extern float SHT3x_CalcTemperatureC_F(void); extern float SHT3x_CalcRelativeHumidity_F(void); extern float GetTemperatureC_F(void); extern float GetRelativeHumidity_F(void); extern UINT_8 IsSHT31MeasureDone(void); #endif <file_sep>/Curiosity_1619.X/SourceFiles/SunSensor/AD.h /** @file ad.h * @ingroup SunSensor * * @author <NAME> * * */ #ifndef _AD_H_ #define _AD_H_ #include "../COS/COS_Defs.h" /*-- Includes --*/ typedef enum { AD_MEASURE_START, AD_MEASURE_GetResult, AD_MEASURE_WAIT, }AD_tt; extern void AD_Task(void); extern float GetNtcTemp(void); extern UINT_8 IsADMeasureDone(void); #endif <file_sep>/Curiosity_1619.X/SourceFiles/SunSensor/AD.c /** @file AD.c * @ingroup SunSensor * * @author <NAME> * * */ /*-- Includes --*/ #include "../../mcc_generated_files/mcc.h" #include "AD.h" #include "../COS/COS_Defs.h" AD_tt AD_State = AD_MEASURE_START; UINT_16 AD_Result; static UINT_8 TimerCounter; static UINT_8 IsMeasureDone; void AD_Task(void) { UINT_8 str[8]; switch(AD_State) { case AD_MEASURE_START: ADC_SelectChannel(4); ADC_StartConversion(); AD_State = AD_MEASURE_GetResult; break; case AD_MEASURE_GetResult: if (ADC_IsConversionDone) { AD_Result = ADC_GetConversionResult(); IsMeasureDone = TRUE; // sprintf(str, "%d" , AD_Result); // // EUSART_Write('A'); // EUSART_Write(str[0]); // EUSART_Write(str[1]); // EUSART_Write(str[2]); // EUSART_Write(str[3]); // EUSART_Write(str[4]); AD_State = AD_MEASURE_WAIT; } break; case AD_MEASURE_WAIT: TimerCounter++; if (TimerCounter > 50) { TimerCounter = 0; AD_State = AD_MEASURE_START; } break; default: break; } } float GetNtcTemp(void) { float NtcTemp; if (AD_State > 100) { NtcTemp = 25.53; } else { NtcTemp = -20.96; } return NtcTemp; } UINT_8 IsADMeasureDone(void) { return IsMeasureDone; } <file_sep>/Curiosity_1619.X/SourceFiles/COS/COS_Main.h /** @file COS_Main.h * @ingroup group_COS_Setup * * @author <NAME> * @author <NAME> * * */ #ifndef COS_MAIN_H #define COS_MAIN_H #include "COS_UserTskList.h" /******************************************************************************/ /****************************** DECLARATIONS **********************************/ /******************************************************************************/ /* COS Declarations */ #ifdef _UNIT_TESTING_ #undef _COS_LIN_ENABLED #endif // _UNIT_TESTING_ #ifdef _COS_LIN_ENABLED #define TSK_COUNT (USER_TSK_COUNT+2) /* Number of tasks called by the task manager */ #else #define TSK_COUNT USER_TSK_COUNT /* Number of tasks called by the task manager */ #endif // _COS_LIN_ENABLED #define NUM_TSKS TSK_COUNT /* number of routines called by the task manager */ #define COS_TSK_SLT SLOT_TIME /* basic task slot time in milliseconds */ #define TIME_TSK_EVERYSLOT SLOT_TIME /* EVERYSLOT task time in msec */ #define TIME_TSK_HALFSPEED (SLOT_TIME*2) /* HALFSPEED task time in msec */ #define TIME_TSK_QUARTERSPEED (SLOT_TIME*4) /* QUARTERSPEED task time in msec */ #define TIME_TSK_EIGHTHSPEED (SLOT_TIME*8) /* EIGHTHSPEED task time in msec */ /* COS Task Slot Deeclarations */ #define TSK_EVERYSLOT 0xff /* Runs every SLOT_TIME */ #define TSK_HALFSPEED_S1 0xaa /* Runs every odd SLOT_TIME */ #define TSK_HALFSPEED_S2 0x55 /* Runs every even SLOT_TIME */ #define TSK_QUARTERSPEED_S1 0x88 /* Runs in Slot 1 and Slot 5 */ #define TSK_QUARTERSPEED_S2 0x44 /* Runs in Slot 2 and Slot 6 */ #define TSK_QUARTERSPEED_S3 0x22 /* Runs in Slot 3 and Slot 7 */ #define TSK_QUARTERSPEED_S4 0x11 /* Runs in Slot 4 and Slot 8 */ #define TSK_EIGHTHSPEED_S1 0x80 /* Runs in Slot 1 */ #define TSK_EIGHTHSPEED_S2 0x40 /* Runs in Slot 2 */ #define TSK_EIGHTHSPEED_S3 0x20 /* Runs in Slot 3 */ #define TSK_EIGHTHSPEED_S4 0x10 /* Runs in Slot 4 */ #define TSK_EIGHTHSPEED_S5 0x08 /* Runs in Slot 5 */ #define TSK_EIGHTHSPEED_S6 0x04 /* Runs in Slot 6*/ #define TSK_EIGHTHSPEED_S7 0x02 /* Runs in Slot 7 */ #define TSK_EIGHTHSPEED_S8 0x01 /* Runs in Slot 8 */ #define COS_SLOT_1 TSK_EIGHTHSPEED_S1 #define COS_SLOT_2 TSK_EIGHTHSPEED_S2 #define COS_SLOT_3 TSK_EIGHTHSPEED_S3 #define COS_SLOT_4 TSK_EIGHTHSPEED_S4 #define COS_SLOT_5 TSK_EIGHTHSPEED_S5 #define COS_SLOT_6 TSK_EIGHTHSPEED_S6 #define COS_SLOT_7 TSK_EIGHTHSPEED_S7 #define COS_SLOT_8 TSK_EIGHTHSPEED_S8 /* COS Vars */ extern UINT_8 COS_tsk_msk; /* Mask for tasks to run this time slice */ extern UINT_8 COS_tsk_ind; /* Index into COS tasks array */ extern UINT_8 COS_tsk_ena; /* COS task enable flag */ extern UINT_16 COS_tsk_tmr; /* task slot timer */ extern UINT_16 COS_tcnt_val; /* value of Timer count register */ extern UINT_16 COS_tcnt_lst; /* Timer count at last ms interval */ extern UINT_16 COS_ms_tmr; /* Task manager ms timer */ extern volatile UINT_16 COS_sec_tmr; /* second timer */ /* COS Prototypes */ void COS_Init(void); /* Call this before main loop to configure the task manager */ void COS_TimerSetup(void); /* Prototype for setting up base tick */ void COS_TmrHandler(void); /* Call as below in main loop */ void COS_TskMan(void); /* Call as below in main loop */ #ifdef DEBUG_COS_TSK_TIMES void DebugTaskTimerInit(void); #ifndef _UNIT_TESTING_ #warning Warning! COS Debug Enabled! Do not commit! Do not release! Warning! #endif #endif #ifdef _UNIT_TESTING_ #include "UnitHelper_COS_main.h" #endif #endif /* COS_MAIN_H */ <file_sep>/Curiosity_1619.X/SourceFiles/SunSensor/I2C_Driver.c #include "I2C_Driver.h" #include <xc.h> #define SDA LATBbits.LATB4 #define SCL LATBbits.LATB6 void I2C_Init(void) { SSP1STAT = 0x00; SSP1CON1 = 0x08; SSP1CON2 = 0x00; SSP1ADD = 0x27; SSPEN = 1; //Enable MSSP SSP1IF = 0; SSP1IE = 1; } void I2C_Init_IO(void) { SDA = LOW; SCL = LOW; SDA = HIGH; SCL = HIGH; } void I2C_StartCondition_IO(void) { SDA = HIGH; SCL = HIGH; SDA = LOW; __delay_us(10); SCL = LOW; __delay_us(10); } UINT_8 I2C_WriteByte_IO (UINT_8 txByte) { UINT_8 mask,error=0; for (mask=0x80; mask>0; mask>>=1) //shift bit for masking (8 times) { if ((mask & txByte) == 0) { SDA=LOW;//masking txByte, write bit to SDA-Line } else { SDA=HIGH; } __delay_us(1); //data set-up time (t_SU;DAT) SCL=HIGH; //generate clock pulse on SCL __delay_us(10); //SCL high time (t_HIGH) SCL=LOW; __delay_us(1); //data hold time(t_HD;DAT) } SDA=HIGH; //release SDA-line SCL=HIGH; //clk #9 for ack __delay_us(1); //data set-up time (t_SU;DAT) if(SSP1CON2&0x40 == HIGH) error=ACK_ERROR; //check ack from i2c slave SCL=LOW; __delay_us(20); //wait time to see byte package on scope return error; //return error code } void I2C_StartCondition(void) { SSP1IF = 0; SSP1CON2bits.SEN = 1; // initiate start condition while(!SSP1IF); SSP1IF = 0; } void I2C_StopCondition(void) { SSP1IF = 0; SSP1CON2bits.PEN = 1; // initiate stop condition while(!SSP1IF); SSP1IF = 0; } void I2C_MasterSendAck(void) { SSP1CON2bits.ACKDT = 0; SSP1CON2bits.ACKEN = 1; } void I2C_MasterSendNack(void) { SSP1CON2bits.ACKDT = 1; SSP1CON2bits.ACKEN = 1; } UINT_8 I2C_WriteByte (UINT_8 txByte) { UINT_8 ack; ack = 0; SSP1IF = 0; SSP1BUF = txByte; while(!SSP1IF); SSP1IF = 0; SSP1STAT = 0; ack |= SSP1CON2&0x40; return ack; //return ACK (0) or NACK(1) } UINT_8 I2C_ReadByte (UINT_8 ack) { UINT_8 rxByte; rxByte=0; SSP1CON2bits.RCEN = 1; // initiate read sequence while(!SSP1IF); // wait for read complete SSP1IF = 0; // clear interrupt flag rxByte = SSP1BUF; // read received byte if(ack == 0)SSP1CON2bits.ACKDT = 0; // set up to ACK or NACK according to ack parameter else SSP1CON2bits.ACKDT = 1; // set up to ACK or NACK according to ack parameter SSP1IF = 0; SSP1CON2bits.ACKEN = 1; // enable ack while(!SSP1IF); SSP1IF = 0; return rxByte; //return read byte }<file_sep>/Curiosity_1619.X/SourceFiles/SunSensor/Led.c /** @file Led.c * @ingroup SunSensor * * @author <NAME> * * */ /*-- Includes --*/ #include "../../mcc_generated_files/mcc.h" #include "Led.h" #define BreathLedPhease1 100//(500/SLOT_TIME) #define BreathLedPhease2 200//(1000/SLOT_TIME) #define BreathLedPhease3 100//(500/SLOT_TIME) #define HighLimitRatio 80 //Percent #define HighLimitDutyValue 400//(HighLimitRatio * 4 * (PR2 + 1) / 100) #define TimeSlotPerRiseRatio 4//(HighLimitDutyValue/BreathLedPhease1) #define TimeSlotPerDownRatio 2//(HighLimitDutyValue/BreathLedPhease2) static uint16_t counter; static uint8_t BreathState = 1; static uint8_t TimeSlotCounter; static uint16_t dutyValue; static uint8_t Timer2Flag; void Led2_PWM(void) { switch (BreathState) { case 1: counter++; if(counter > BreathLedPhease1) { BreathState = 2; } else { dutyValue += TimeSlotPerRiseRatio; } break; case 2: counter++; if (counter >= (BreathLedPhease1 + BreathLedPhease2)) { BreathState = 3; dutyValue = 0; //counter = 0; } else { if (dutyValue > 0) { if (dutyValue > TimeSlotPerDownRatio) { dutyValue-=TimeSlotPerDownRatio; } else { dutyValue = 0; } } } break; case 3: counter++; if (counter > (BreathLedPhease1 + BreathLedPhease2 + BreathLedPhease3)) { counter = 0; BreathState = 1; } break; default: break; } PWM3_LoadDutyValue(dutyValue); } void LedBreathControl(void) { IO_RA2_Toggle(); } <file_sep>/Curiosity_1619.X/SourceFiles/SunSensor/Led.h /** @file Led.c * @ingroup SunSensor * * @author <NAME> * * */ #ifndef _LED_H_ #define _LED_H_ /*-- Includes --*/ extern void Led2_PWM(void); extern void LedBreathControl(void); #endif <file_sep>/Curiosity_1619.X/SourceFiles/SunSensor/UART_Display.h /** @file Led.c * @ingroup SunSensor * * @author <NAME> * * */ #ifndef _UART_DISPLAY_ #define _UART_DISPLAY_ /*-- Includes --*/ #include "../../mcc_generated_files/mcc.h" typedef enum { UART_TEMP, UATR_HUMI, UART_NTC, UART_Refresh_Interval, }UART_tt; extern void SendByUart(uint8_t Txt); extern void UartDisplay(void); #endif <file_sep>/Curiosity_1619.X/SourceFiles/COS/COS_UserTskList.c /** @file COS_UserTskList.c * @ingroup group_COS_Setup * * @author <NAME> * @author <NAME> * * */ /*-- Includes --*/ #include "GlobalDef.h" #include "COS_UserTskList.h" #include "../SunSensor/Led.h" #include "../SunSensor/UART_Display.h" #include "../SunSensor/SHT25.h" #include "../SunSensor/AD.h" /** @var const task COS_tsk[NUM_TSKS] * * @brief COS Task List * * This array of tasks and speed/slot definitions defines exactly what the COS * will run and how often. * * Example Task Definition: * @code const task COS_tsk[NUM_TSKS] = /* Task array for task manager { { WDT_Trigger, TSK_EVERYSLOT }, { LIN_StatusHand, TSK_HALFSPEED_S2 } }; * @endcode * * @ingroup group_COS_Setup */ const task COS_tsk[NUM_TSKS] = /* Task array for task manager */ { //////////////////////////////////////////////////////////////////////////////// /////////////////////////// Start User Setup /////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //{SHT25_StateMachine, TSK_EIGHTHSPEED_S1}, //{AD_Task, TSK_EIGHTHSPEED_S2}, //{UartDisplay, TSK_EIGHTHSPEED_S8}, {Led2_PWM, TSK_EVERYSLOT} //////////////////////////////////////////////////////////////////////////////// //////////////////////////// End User Setup //////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /* Example using prototypes in COS_UserSetup.h * * { WDT_Trigger, TSK_EVERYSLOT }, // watchdog service handler * { ACQ_StateMachine, TSK_EVERYSLOT }, // Sunload Sensor ACQuistion State Machine * { CALC_StateMachine, TSK_EVERYSLOT }, // Sunload Sensor CALCulation State Machine * { LIN_SignalHandler, TSK_EVERYSLOT }, // LIN signal handler * { LIN_StatusHand, TSK_EVERYSLOT } // LIN status handler * * These tasks must be defined in their own C files which #include this H file * Every task must take void arguments and return void */ }; <file_sep>/Curiosity_1619.X/SourceFiles/COS/COS_UserTskList.h /** @file COS_UserTskList.c * @ingroup group_COS_Setup * * @author <NAME> * @author <NAME> * * */ #ifndef COS_USERTSKLIST_H #define COS_USERTSKLIST_H /* Include GlobalDef.h in all C files */ #include "GlobalDef.h" //////////////////////////////////////////////////////////////////////////////// /////////////////////////// Start User Setup /////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /*********** User Defined Includes for Task Prototypes ***********/ /*********** Task Setup ***********/ /* MUST be equal to number of user-defined tasks in COS_tsk[] */ #define USER_TSK_COUNT 3 /* Number of user-defined tasks called by the task manager */ /* DO NOT COUNT LIN RELATED TASKS */ #define SLOT_TIME 5 /* Basic task slot time in milliseconds (8 and 10 work well) */ //////////////////////////////////////////////////////////////////////////////// //////////////////////////// End User Setup //////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /* COS Structs */ typedef struct { void (*tptr) (void); UINT_8 sched; } task; extern const task COS_tsk[]; /* Array of COS tasks */ #endif /* COS_USERTSKLIST_H */
340601efddb28a4bd0d5f653172cf36dcff2ec6b
[ "C", "Makefile" ]
18
C
phkakaka/Curiosity_1619_4.01
e9eb3cf4a0668b14762aa19a63a3314de817d778
1d4ed22ad77e88b7f0c941828eb775b10eefb702
refs/heads/master
<repo_name>warowatto/poin2server<file_sep>/module/EventModule.js const Observable = require('rxjs').Observable; const db = require('./DatabaseModule'); const dateFormat = require('./DateConvertModule'); function eventCheck(productId, eventId, userId) { // 현재 날짜 let now = dateFormat.dateFormat(Date()); // 상품 기본가 가져오기 let prodcutQuery = `SELECT defaultPrice FROM Products WHERE id = ${productId}`; let productNotFoundError = { message: '존재하지 않는 상품입니다' }; let productObserver = db.query(prodcutQuery, null, productNotFoundError).take(1); // 이벤트 정보 가져오기 let eventColum = db.colum( 'Events.productId as productId', 'EventType.targetUser as targetUser', 'EventType.repeatCount as repeatCount', 'EventType.discount as discount'); let eventQuery = `SELECT ${eventColum} FROM Events LEFT JOIN EventType ON Events.eventType = EventType.id WHERE Events.start_at <= '${now}' AND Events.end_at >= '${now}'`; let eventNotFoundError = { message: '존재하지 않는 이벤트 입니다' } let eventObserver = db.query(eventQuery, null, eventNotFoundError).take(1); // 사용자 이벤트 참여횟수 가져오기 let userUseEventColum = db.colum('COUNT(id) as count'); let userUseEventCountQuery = `SELECT ${userUseEventColum} FROM Payments WHERE userId = ${userId} AND eventId = ${eventId}`; let userUseEventCountObserver = db.query(userUseEventCountQuery, null).take(1); // 반환 (실제가격, 할인금액) return Observable.zip(eventObserver, productObserver, userUseEventCountQuery, (event, product, use) => { if (use.count == null || use.count < event.repeatCount) { // 이벤트 참여기록이 없거나 이벤트 참여횟수 미달인 사용자에 한해 // 이벤트 대상자로 취급 return { discount: event.discount, defaultPrice: product.defaultPrice, totalAmount: product.defaultPrice - event.discount }; } else { // 이벤트 대상자가 아닌 경우 return { discount: 0, defaultPrice: product.defaultPrice, totalAmount: product.defaultPrice }; } }); } module.exports = { eventCheck: eventCheck };<file_sep>/module/EncrytionModule.js const crypto = require('crypto'); const key = 'payot_encrypt_key'; // 암호화 function encrypt(text) { let cipher = crypto.createCipher('aes-256-cbc', key); let en = cipher.update(text, 'utf8', 'base64'); en += cipher.final('base64'); return en; } // 복호화 function decrypt(text) { let decipher = crypto.createDecipher('aes-256-cbc', key); let de = decipher.update(text, 'base64', 'utf8'); de += decipher.final('utf8'); return de; } // 암호화 가능한 변수인지 체크 function encryptTypeCheck(object) { // 문자열이야 하며 길이가 1보다는 크고 날짜가 아니어야 함 return typeof object == 'string' && object.length > 1 && !(object instanceof Date) } // 객체의 문자열을 암/복호화 function objectEncrypt(object, method) { if (Array.isArray(object)) { object = object.map(item => { return objectEncrypt(item, method) }); } else if(typeof object == 'object') { Object.getOwnPropertyNames(object).forEach(name => { object[name] = objectEncrypt(object[name], method); }); } else { if (encryptTypeCheck(object)) object = method(object); } return object; } module.exports = { object: objectEncrypt, encrypt: encrypt, decrypt: decrypt }<file_sep>/router/event.js const router = require('express').Router(); // 이벤트 목록 router.get(['/', '/:id'], (req, res) => { let id = req.params.id; if(id) { res.json(`이벤트 : ${id}`); } else { res.json('이벤트 목록'); } }); // 이벤트 단일 목록 module.exports = router;<file_sep>/router/user.js const Observable = require('rxjs').Observable; const router = require('express').Router(); const db = require('../module/DatabaseModule'); const iamport = require('../module/PaymentModule'); const event = require('../module/EventModule'); const dateformat = require('../module/DateConvertModule'); const uuid = require('uuid/v4'); const cleanArray = require('clean-array'); const IamporterError = require('iamporter').IamporterError; // 회원정보 가져오기 router.get('/:id', (req, res) => { // 회원아이디 let id = req.params.id; let query = `SELECT * FROM Users WHERE id = ?`; db.query(query, [id], '유저 없음') .take(1) .subscribe( user => { res.json(user); }, err => { res.json(err); } ); }); router.post('/login', (req, res) => { // 로그인 플래폼 let flatform = req.body.flatform; // 플래폼 인증 토큰 let token = req.body.token; getUser(flatform, token) .subscribe( user => { // 로그인 정보와 회원정보가 둘다 있는 경우 res.status(200).json(user); }, err => { console.log(err); if (err == 'Not Found User') { // 로그인 정보가 없는 경우 res.status(403).json({ message: 'Not Found User' }); } else if (err == 'NotSigned User') { // 로그인 정보는 있지만 회원가입이 이루어지지 않은 경우 res.status(404).json({ message: 'Not Signed User' }); } else { // 서버의 오류가 발생한 경우 res.status(500).json({ message: 'Server Error' }); } }); }); // 플래폼과 토큰으로 사용자정보 가져오기 function getUser(flatform, token) { // 회원 로그인 정보 let signinQuery = `SELECT userId FROM SocialLogin WHERE hash = ?`; let queryParams = `${flatform}:${token}`; // 회원 상세 정보 let userColums = db.colum('*') let userFindQuery = `SELECT ${userColums} FROM Users WHERE id = ?`; // 회원 카드 정보 let cardColums = db.colum('id, bankName, displayName, create_at'); let cardFindQuery = `SELECT ${cardColums} FROM Cards WHERE userId = ?`; // DB에서 회원 로그인 정보를 찾고, return db.query(signinQuery, [queryParams], 'Not Found User') .flatMap(sign => { // 로그인 정보가 있다면 추가 회원정보를 로드 let userId = sign.userId; return db.query(userFindQuery, [userId], 'Not Signed User'); }) .flatMap(user => { // 회원정보와 카드정보를 병합 return Observable.zip( Observable.of(user), db.query(cardFindQuery, [user.id]).toArray() .map(cards => { let myCard = cleanArray(cards); if (myCard.length == 0) { return null; } else { return cleanArray(cards); }}), (user, cards) => { user.cards = cards; return user; } ) }); } // 회원가입 router.post('/', (req, res) => { let flatform = req.body.flatform; let token = req.body.token; // 회원 상세정보 등록 let insertQuery = `INSERT INTO Users SET ?`; let insertValue = { name:req.body.name, gender: req.body.gender, profileImage: req.body.profileImage, thumbnailImage: req.body.thumbnailImage, create_at: new Date() }; // 회원 로그인 정보 등록 let insertLoginColums = db.colum('hash', 'flatform', 'userId', 'create_at'); let insertLoginQuery = `INSERT INTO SocialLogin SET ?`; // 회원 정보를 등록 이후 db.update(insertQuery, insertValue, 'Already Signed User') .flatMap(info => { // 로그인 상태정보를 등록한다 let insertId = info.insertId; let insertLoginValue = { hash: `${flatform}:${token}`, flatform: flatform, userId: insertId, create_at: new Date() }; let inserLoginObserver = db.update(insertLoginQuery, insertLoginValue); return Observable.zip(Observable.of(insertId), inserLoginObserver, (userId, inserted) => { return userId; }); }) .flatMap(userId => { // 등록 이후 회원정보를 로드 return getUser(flatform, token); }) .subscribe( user => { // 사용자 정보를 출력한다 res.status(200).json(user); }, err => { res.status(400).json({ message: '이미 가입된 계정입니다' }); } ); }); // 회원정보 수정 router.put('/', (req, res) => { // 회원 정보 수정 }); // 회원 탈퇴 router.delete('/:flatform/:token', (req, res) => { // 유저 찾기 쿼리 let userFindQuery = `SELECT userId FROM SocialLogin WHERE hash = ?`; let userFindParams = `${req.params.flatform}:${req.params.token}`; // 로그인 테이블 탈퇴 등록 // 소셜로그인의 종류가 많은경우 모두 헤지 처리 let updateLoginQuery = `UPDATE SocialLogin SET remove_at = 'NOW()' WHERE userId = ?`; // 회원정보 테이블 정보 삭제 let deleteUserQuery = `DELETE FROM Users WHERE id = ?`; db.query(userFindQuery, [userFindParams], 'Not Signed User') .flatMap(user => { let userId = user.userId; let updateLoginQuery = db.update(updateLoginQuery, [user.id]); let deleteUserQuery = db.update(deleteUserQuery, [userId]); return Observable.zip(updateLoginQuery, deleteUserQuery, (uppdateLogin, deleteUser) => { return true; }); }) .subscribe( state => { res.status(200).json({ result: true }); }, err => { res.status(500).json({ message: 'Server Error' }); } ) }); // 회원 카드등록 router.post('/:userId/card', (req, res) => { let userId = req.params.userId; // 등록될 빌링키 let billingKey = uuid(); console.log(billingKey, req.body.card_number, req.body.expiry, req.body.birth, req.body.pwd_2digit); // 아임포트로부터 빌링키 발급 iamport.registCard( billingKey, req.body.card_number, req.body.expiry, req.body.birth, req.body.pwd_2digit) .flatMap(result => { console.log(result); // 빌링키가 성공적으로 발급됬다면 let cardInsertParams = { userId: userId, billingKey: result.data.customer_uid, bankName: result.data.card_name, displayName: req.body.displayName, create_at: new Date() } let cardInsertQuery = `INSERT INTO Cards SET ?`; // 카드테이블에 추가 return db.update(cardInsertQuery, cardInsertParams) }) .flatMap(result => { console.log(result); let insertId = result.insertId; let colum = db.colum('id', 'bankName', 'displayName', 'create_at'); let cardSelectQuery = `SELECT ${colum} FROM Cards WHERE id = ?`; // 카드 정보 가져오기 return db.query(cardSelectQuery, [insertId], '카드 등록 오류') }) .subscribe( card => { res.status(200).json(card); }, err => { console.log("err : " + err); if (err == 'Validation Execption') { res.status(400).json(err); } else if (err instanceof IamporterError) { res.status(400).json(err.IamporterError); } else { res.status(500).json(err); } } ); }); // 사용자 카드삭제 router.delete('/:userId/card/:cardId', (req, res) => { let userId = req.params.userId; let cardId = req.params.cardId; let cardColums = db.colum('userId', 'billingKey'); let cardSelectQuery = `SELECT ${cardColums} FROM Cards WHERE id = ${cardId}`; db.query(cardSelectQuery, null, { message: '등록된 카드가 아닙니다' }) .flatMap(card => { let userId = card.userId; let billingKey = card.billingKey; return iamport.removeCard(billingKey) }) .flatMap(result => { let cardDeleteQuery = `DELETE FROM Cards WHERE id = ${cardId}`; return db.update(cardDeleteQuery, null); }) .subscribe( result => { res.status(200).json({ message: '카드가 성공적으로 삭제되었습니다' }); }, err => { res.status(500).json(err); } ); }); // 사용자 결제 // 사용자의 결제는 포인트 및 현금으로 결제 가능하다. // 장비가 동작하는 금액과 실제 결제되는 금액은 다를 수 있다. // 포인트 결제시 포인트누적은 해당되지 않는다. // 포인트 + 현금을 통한 지불은 (가능)하다 // 포인트 + 이벤트는 (가능)하다 // 포인트는 결제한 현금에 대해 3%로 적용 된다. router.post('/:userId/payment', (req, res) => { // 입력 파라미터 정보 let userId = req.params.userId; let cardId = req.body.cardId; let machineId = req.body.machineId; let productId = req.body.productId; let amount = req.body.amount; // 결제번호 let paymentNumber = uuid(); // 장치정보 가져오기 let deviceFindQuery = `SELECT * FROM Machines WHERE id = ?;`; let deviceFindObserver = db.query(deviceFindQuery, [machineId]); // 카드 정보 가져오기 let cardSelectQuery = `SELECT * FROM Cards WHERE id = ${cardId}`; let cardGetObserver = db.query(cardSelectQuery, null, 'NOT FOUND CARD'); // 오픈 이벤트 대상자 검색 let eventTargetQuery = `SELECT COUNT(eventId) as count FROM Payments WHERE userId = ?;`; let eventTargetObserver = db.query(eventTargetQuery, [userId]) .map(result => { console.log(result); return result.count < 3; }); // 결제 내역 등록 let paymentAppendQuery = `INSERT INTO Payments SET ?;`; // 포인트 적립 let pointAppendQuery = `UPDATE Users SET point = point + ? WHERE id = ?`; // 결제등록을 위한 정보 가져오기 Observable.zip(deviceFindObserver, cardGetObserver, eventTargetObserver, (device, card, target) => { let eventId = target ? 1 : null; let eventAmount = target ? 0 : amount; console.log(device, target); return { // 결제이후 삭제 billingKey: card.billingKey, // 이벤트 확인 이후 target: target, /////////// userId: userId, companyId: device.companyId, cardId: card.id, eventId: eventId, machineId: device.id, productId: productId, defaultPrice: amount, amount: eventAmount, pay_at: dateformat.dateFormat(new Date()) }; }) .flatMap(info => { // 결제하기 let billingKey = info.billingKey; delete info.billingKey; info.id = uuid(); // 이벤트가로 결제를 할 필요가 없다면 if (info.amount == 0) { return Observable.of(info); } else { return iamport.payment(billingKey, info.id, info.amount) .map(result => { return info; }) } }) .flatMap(info => { let isEvent = info.target; delete info.target; // 결제가 완료되었다면 포인트 적립과 DB에 기록을 한다 let insertDB = db.update(paymentAppendQuery, info); if (isEvent) { // 이벤트로 결제된 사항은 포인트를 누적하지 않음 return insertDB.map(result => { return info }); } else { // 일반결제시에는 포인트 누적 10% let point = info.amount * 0.1; let pointAppendObserver = db.update(pointAppendQuery, [point, userId]); return Observable.zip(insertDB, pointAppendObserver, (payments, points) => { return info; }); } }) .subscribe( info => { res.status(200).json(info); }, err => { if (err instanceof IamporterError) { console.log(err); console.log(err.status); // HTTP STATUS CODE console.log(err.message); // 아임포트 API 응답 메시지 혹은 Iamporter 정의 메시지 console.log(err.data); // 아임포트 API 응답 데이터 console.log(err.raw); // 아임포트 API RAW DATA res.status(400).json({ result: 'error', message: err.message }); } else { res.status(500).json({ result: 'error', message: err }); } } ); }); router.post('/payback', (req, res) => { let paymentId = req.body.paymentId; let removePayments = `DELETE FROM Payments WHERE id = ?`; }); // 회원의 결제 내역 가져오기 router.get('/:userId/payment', (req, res) => { let userId = req.params.userId; // let colum = db.colum('*'); let colum = db.colum( 'Payments.amount as amount', 'Payments.pay_at as pay_at', 'Machines.displayName as machineName', 'Products.name as productName' ); let query = `SELECT ${colum} FROM Payments LEFT OUTER JOIN Machines ON Machines.id = Payments.machineId LEFT OUTER JOIN Cards ON Cards.id = Payments.cardId LEFT OUTER JOIN Products ON Products.id = Payments.productId WHERE Payments.userId = ${userId};`; db.query(query) .toArray() .map(item => { return cleanArray(item); }) .subscribe( item => { if (item.length == 0) { res.status(404).json(item); } else { res.status(200).json(item); } }, err => { res.status(500).json(err); } ); }); module.exports = router;<file_sep>/module/DateConvertModule.js const format = require('dateformat'); // 날짜 변환 function dateFormat(date) { return format(date, 'yyyy-mm-dd'); } // 날짜시간 변환 function dateTimeFormat(date) { return format(date, 'yyyy-mm-dd HH:MM:ss'); } module.exports = { dateFormat: dateFormat, dateTimeFormat: dateTimeFormat }<file_sep>/router/install.js const Observable = require('rxjs').Observable; const router = require('express').Router(); const db = require('../module/DatabaseModule'); const hash = require('../module/password'); router.get('/types', (req, res) => { let query = `SELECT * FROM MachineTypes`; db.query(query, []) .subscribe( result => { res.status(200).json(result); }, err => { res.status(500).json({ message: err }); }); }); router.post('/login', (req, res) => { let email = req.body.email; let password = req.body.password; let findCompany = `SELECT * FROM Companys WHERE email = ?;`; let findUser = db.query(findCompany, [email]); findUser.flatMap(result => { let salt = result.salt; let dbpassword = result.password; return hash.getHash(password, salt) .map(resultHash => { return { saveHash: dbpassword, nowHash: resultHash, company: result } }) }).subscribe( result => { res.status(200).json(result); }, err => { res.status(404).json({ message: err }) } ) }); router.post('/machine', (req, res) => { let companyId = req.body.companyId; let macAddress = req.body.macAddress; let deviceName = req.body.deviceName; let displayName = req.body.displayName; let typeId = req.body.typeId; let description = req.body.description; let insertMachineQuery = `INSERT INTO Machines SET ?;`; let machineParams = { companyId: companyId, macAddress: macAddress, deviceName: deviceName, displayName: displayName, typeId: typeId, description: description, create_at: new Date() } db.query(insertMachineQuery, [machineParams]) .flatMap(result => { let insertId = result.insertId; let query = `SELECT * FROM Machines WHERE id = ?;`; return db.query(query, [insertId]) }) .subscribe( result => { res.status(200).json(result); }, err => { res.status(404).json({ message: err }); } ) }); module.exports = router;
cbda9ced6118eb7868143384972bbedb560c230a
[ "JavaScript" ]
6
JavaScript
warowatto/poin2server
fcbff5d227d76fcc1f9c558adcbd6ef20e9b7988
28e41bb8b1da8957906bff8703db5a8a36003e9e
refs/heads/master
<file_sep>//Answer 1 var people = [ ['jose', 28], ['francis', 20], ['henrietta', 25] ]; people.push(['John' , 35]); //Answer 2 var food = [ ['banana', 'lemon', 'strawberry'], ['almond', 'pecan', 'pistachio'], ['carrot', 'potato', 'beet'] ]; console.log(food[2][1]); //Answer 3 var a = " and I create web applications." var job = "Web Developer"; var b = "Hello, I am a "; console.log(b + job + a); //Answer 4 console.log("FirstLine \n \'SecondLine' \n \ \ \ ThirdLine"); //Answer 5 result = "moocluck"; //Answer 6 13 //Answer 7 6 //Answer 8 60 //Answer 9 66 //Answer 10 class Athlete{ constructor(name , age , sex , height , weight , marks){ this.name = name; this.age = age; this.sex = sex; this.height = height; this.weight = weight; this.marks = marks; } } //Answer 11 Athlete.prototype.getMarksAverage = function(){ var result = 0; for(var i = 0 ; i < this.marks.length ; i++){ result+=this.marks[i]; } return result/this.marks.length; } var a = new Athlete("as" , 2, "F" , 12 , 12, [1,2,3,4,5]); console.log(a.getMarksAverage()); //Answer 12 var a = new Athlete("as" , 2, "F" , 12 , 12, [1.2,2.6,3.5,4.2,5.1]); Athlete.prototype.getRoundedMarks = function(){ return this.marks.map(function(item){ return Math.round(item); }); } console.log(a.getRoundedMarks()); //Answer 13 class Point2D{ constructor(x , y){ this.x = x; this.y = y; } } // //Answer 14 class Rectangle{ constructor(Point2D , height , width){ this.Point2D = Point2D; this.height = height; this.width = width; } } //Answer 15 class Rectangle{ constructor(Point2D , height , width){ this.Point2D = Point2D; this.height = height; this.width = width; } getArea(){ return this.width * this.height; } } //Answer 16 function getTotalCoverage(rectArr){ return rectArr.map(function(item){ return item.getArea(); }).reduce(function(prev,curr){ return prev+curr; }); }
462f85ea674b372d1ab505fd3fb735afa95a3715
[ "JavaScript" ]
1
JavaScript
imbernal/web2010-Test1
0704725cb7800980b12079fc9b3c39fa1c4d7890
1b7197e84716d16e6c021bbf07340be800acc031
refs/heads/master
<file_sep>import Foundation class DataContext { private(set) var users:[User] = [] func addUser(user: User) { addUsers(users: [user]) } func addUsers(users: [User]) { self.users += users } } <file_sep>// // MockCamera.swift // UserInputForm // // Created by sm-user on 14.11.2017. // Copyright © 2017 Studio Mobile. All rights reserved. // import Foundation class MockCamera { } <file_sep>// // UserCardViewModel.swift // UserInputForm // // Created by sm-user on 12.11.2017. // Copyright © 2017 Studio Mobile. All rights reserved. // import UIKit class UserCardViewModel { let dataContext: DataContext let storageService: StorageService init(dataContext: DataContext, storageService: StorageService) { self.dataContext = dataContext self.storageService = storageService } func loadImage(index: Int) -> UIImage? { return storageService.loadImage(index: index) } func getUserPropertiesForIndex(index: Int)->(String, String?, String) { let user = dataContext.users[index] return (surname: user.surname, name: user.name, birthday: user.birthDate) } } <file_sep>import UIKit class ViewModel { let dataContext: DataContext let storageService: StorageService init(dataContext: DataContext, storageService: StorageService) { self.dataContext = dataContext self.storageService = storageService } func getUser(index: Int) -> User { return getUsers()[index] } func getUsers() -> [User] { return dataContext.users } func saveImage(image: UIImage) { storageService.saveImage(image: image, index: getUsersCount()) } func loadImage(index: Int) -> UIImage? { return storageService.loadImage(index: index) } func addUser(user: User) { dataContext.addUser(user: user) } func getUsersCount() ->Int { return dataContext.users.count } func saveData() { storageService.encodeUsers(users: dataContext.users) } func loadData() { dataContext.addUsers(users: storageService.decodeUsers()) } } <file_sep>// // ViewController.swift // UserInputForm // // Created by User on 04/11/2017. // Copyright © 2017 Studio Mobile. All rights reserved. // import UIKit class ViewController: UIViewController { var mainView: MainView { get { return view as! MainView } } private let reuseIdentifierUser = "user" var viewModel: ViewModel? var imagePicker: UIImagePickerController = { let imagePicker = UIImagePickerController() imagePicker.sourceType = .savedPhotosAlbum; imagePicker.allowsEditing = false return imagePicker }() override func loadView() { view = MainView() mainView.assignActions(userButtonAction: addUserButtonAction, takePhotoAction: takePhoto) viewModel!.loadData() } @objc func addUserButtonAction(sender: UIButton!) { let (surname, name, birthDate) = mainView.inputUserView.textFieldValues() guard !surname.isEmpty && !birthDate.isEmpty else { let message = surname.isEmpty ? "Please, fill surname field" : "Please, fill birthday field" let alertController = UIAlertController(title: "Error", message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) navigationController?.present(alertController, animated: true, completion: nil) return } let user = User(surname: surname, name: name, birthDate: birthDate) viewModel!.addUser(user: user) mainView.inputUserView.emptyAllTextFields() mainView.userTableView.reloadData() viewModel!.saveData() } init(dataContext: DataContext, storageService: StorageService) { viewModel = ViewModel(dataContext: dataContext, storageService: storageService) super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func handleUserCellPress(index: Int) { let userCardViewController = UserCardViewController(dataContext: viewModel!.dataContext, storageService: viewModel!.storageService, userIndex: index) navigationController?.pushViewController(userCardViewController, animated: true) } override func viewDidLoad() { super.viewDidLoad() mainView.userTableView.register(UserCell.self, forCellReuseIdentifier: reuseIdentifierUser) mainView.userTableView.dataSource = self mainView.userTableView.delegate = self imagePicker.delegate = self } } extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel!.getUsersCount() } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierUser, for: indexPath) let userCell = cell as! UserCell let user = viewModel!.getUser(index: indexPath.row) userCell.fillInFields(surname: user.surname, name: user.name, dateOfBirth: user.birthDate, image: viewModel!.loadImage(index: indexPath.row)) return cell } } extension ViewController: UINavigationControllerDelegate, UIImagePickerControllerDelegate { @objc func takePhoto(_ sender: UIButton!) { if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){ self.present(imagePicker, animated: true, completion: nil) } } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage viewModel!.saveImage(image: chosenImage) dismiss(animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } } extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { handleUserCellPress(index: indexPath.row) } } <file_sep>import UIKit let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let url = URL(fileURLWithPath: documentsPath) let usersURL = url.appendingPathComponent("/users.json") class StorageService { func saveImage(image: UIImage, index: Int) { let imageURL = URL(fileURLWithPath: documentsPath).appendingPathComponent("/userImage\(index).jpg") try! UIImageJPEGRepresentation(image, 1.0)?.write(to: imageURL) print("saved photo \(index)") } func loadImage(index: Int) -> UIImage? { let imageURL = URL(fileURLWithPath: documentsPath).appendingPathComponent("/userImage\(index).jpg") return UIImage(contentsOfFile: imageURL.path) } func encodeUsers(users: [User]) { try! JSONEncoder().encode(users).write(to: usersURL) } func decodeUsers()->[User] { do { let data = try Data(contentsOf: usersURL) return try JSONDecoder().decode([User].self, from: data) } catch { print("Can't load the data from JSON file.") } return [] } } <file_sep>// // UserCardView.swift // UserInputForm // // Created by sm-user on 11.11.2017. // Copyright © 2017 Studio Mobile. All rights reserved. // import UIKit let fontsize = CGFloat(integerLiteral: 20) class UserCardView: UIView { private let imageView = UIImageView() private let nameLabel: UILabel = { let name = UILabel() name.font = name.font.withSize(fontsize) name.text = "name: " return name }() private let surnameLabel: UILabel = { let surname = UILabel() surname.font = surname.font.withSize(fontsize) surname.text = "surname: " return surname }() private let birthdayLabel: UILabel = { let birthday = UILabel() birthday.font = birthday.font.withSize(fontsize) birthday.text = "date of birth: " return birthday }() override init(frame: CGRect) { super.init(frame: frame) addSubview(nameLabel) addSubview(surnameLabel) addSubview(birthdayLabel) addSubview(imageView) } func setFields(surname: String, name: String?, birthday: String, image: UIImage?) { surnameLabel.text! += surname nameLabel.text! += name! birthdayLabel.text! += birthday imageView.image = image } override var frame: CGRect { didSet { let contentDistance = 20 let labelHeight = 30 let labelHeightWithSpace = labelHeight + contentDistance let contentWidth = Int(self.frame.size.width) - 2 * contentDistance var topBorderDistance = 80 let imageHeight = 300 if imageView.image != nil { imageView.frame = CGRect(x: contentDistance, y: topBorderDistance, width: contentWidth, height: imageHeight) topBorderDistance += imageHeight } surnameLabel.frame = CGRect(x: contentDistance, y: topBorderDistance, width: contentWidth, height: labelHeight) topBorderDistance += labelHeightWithSpace if nameLabel.text! != "name: " { nameLabel.frame = CGRect(x: contentDistance, y: topBorderDistance, width: contentWidth, height: labelHeight) topBorderDistance += labelHeightWithSpace } birthdayLabel.frame = CGRect(x: contentDistance, y:topBorderDistance, width: contentWidth, height: labelHeight) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } <file_sep>// // InputCell.swift // UserInputForm // // Created by sm-user on 09.11.2017. // Copyright © 2017 Studio Mobile. All rights reserved. // import UIKit var formatter: DateFormatter = DateFormatter() class InputUserView: UIView { private let nameTextField: UITextField = { let name = UITextField() name.borderStyle = .roundedRect name.placeholder = "name" return name }() private let surnameTextField: UITextField = { let surname = UITextField() surname.borderStyle = .roundedRect surname.placeholder = "surname" return surname }() private let birthdateTextField: UITextField = { let birthdate = UITextField() birthdate.borderStyle = .roundedRect birthdate.placeholder = "date of birth" let birthdayPicker = UIDatePicker() birthdayPicker.datePickerMode = .date formatter.dateFormat = "dd.MM.yyyy" birthdate.inputView = birthdayPicker birthdayPicker.addTarget(self, action: #selector(dateChanged), for: .valueChanged) birthdate.addTarget(self, action: #selector(setDateOnTextField), for: UIControlEvents.editingDidBegin) return birthdate }() @objc func setDateOnTextField(textField: UITextField) { textField.text = formatter.string(for: (textField.inputView as! UIDatePicker).date) } private let submitButton: UIButton = { let submit = UIButton() submit.backgroundColor = .blue submit.setTitle("addUser", for: .normal) return submit }() private let takePhotoButton: UIButton = { let takePhoto = UIButton() takePhoto.backgroundColor = .blue takePhoto.setTitle("take photo", for: .normal) return takePhoto }() @objc private var submitButtonAction: ((UIButton)->())? @objc private var takePhotoButtonAction: ((UIButton)->())? @objc private func addSubmitButtonAction(sender: UIButton!) { submitButtonAction!(sender) } @objc private func addTakePhotoButtonAction(sender: UIButton!) { takePhotoButtonAction!(sender) } override init(frame: CGRect) { super.init(frame: frame) addSubview(nameTextField) addSubview(surnameTextField) addSubview(birthdateTextField) addSubview(submitButton) addSubview(takePhotoButton) self.backgroundColor = UIColor(red: 230/255, green: 230/255, blue: 250/255, alpha: 1) } func assignSubmitButtonAction(action: @escaping (UIButton!)->()) { self.submitButtonAction = action submitButton.addTarget(self, action: #selector(addSubmitButtonAction), for: .touchDown) } func assignTakePhotoButtonAction(action: @escaping (UIButton!)->()) { self.takePhotoButtonAction = action takePhotoButton.addTarget(self, action: #selector(addTakePhotoButtonAction ), for: .touchDown) } func emptyAllTextFields() { surnameTextField.text = "" nameTextField.text = "" birthdateTextField.text = "" } func textFieldValues() -> (surname: String, name: String, birthdate: String) { return (surnameTextField.text!, nameTextField.text!, birthdateTextField.text!) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func dateChanged(_ sender: UIDatePicker) { print("Helo") birthdateTextField.text = formatter.string(from: sender.date) } override var frame: CGRect { didSet { let frameWidth = Int(self.frame.size.width) let contentDistance = 20 let standartHeight = 30 let contentWidth = frameWidth - 2 * contentDistance let buttonWidth = (frameWidth - 3 * contentDistance) / 2 nameTextField.frame = CGRect(x: contentDistance, y: 20, width: contentWidth, height: standartHeight) surnameTextField.frame = CGRect(x: contentDistance, y: 70, width: contentWidth, height: standartHeight) birthdateTextField.frame = CGRect(x: contentDistance, y: 120, width: contentWidth, height: standartHeight) submitButton.frame = CGRect(x: contentDistance, y: 170, width: buttonWidth, height: standartHeight) takePhotoButton.frame = CGRect(x: buttonWidth + 2 * contentDistance, y: 170, width: buttonWidth, height: standartHeight) } } override func sizeThatFits(_ size: CGSize) -> CGSize { let size = super.sizeThatFits(size) return CGSize(width: size.width, height: 200 + 20) } } <file_sep>// // UserCardViewController.swift // UserInputForm // // Created by sm-user on 11.11.2017. // Copyright © 2017 Studio Mobile. All rights reserved. // import UIKit class UserCardViewController: UIViewController { private let userCardViewModel: UserCardViewModel private let currentUserIndex: Int var viewAsCard: UserCardView { get { return view as! UserCardView } } init(dataContext: DataContext, storageService: StorageService, userIndex: Int) { userCardViewModel = UserCardViewModel(dataContext: dataContext, storageService: storageService) currentUserIndex = userIndex super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { view = UserCardView() let userProperties: (surname: String, name: String?, birthday: String) = userCardViewModel.getUserPropertiesForIndex(index: currentUserIndex) viewAsCard.setFields(surname: userProperties.surname, name: userProperties.name, birthday: userProperties.birthday, image: userCardViewModel.loadImage(index: currentUserIndex)) print("\(currentUserIndex)") view.backgroundColor = .white } } <file_sep>// // UserCell.swift // UserInputForm // // Created by sm-user on 09.11.2017. // Copyright © 2017 Studio Mobile. All rights reserved. // import UIKit class UserCell: UITableViewCell { private let surnameLabel = UILabel() private let birthDateLabel = UILabel() private var nameLabel = UILabel() private var contentHeight = 0 let userImageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit return imageView }() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(surnameLabel) contentView.addSubview(birthDateLabel) contentView.addSubview(nameLabel) contentView.addSubview(userImageView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func fillInFields(surname: String, name: String?, dateOfBirth: String, image: UIImage?) { surnameLabel.text = surname nameLabel.text = name birthDateLabel.text = dateOfBirth userImageView.image = image if (name != nil && name != "") || image != nil { contentHeight = 80 } } override var frame: CGRect { didSet { let space = 10 let imageSize = 60 let labelWidth = 150 let labelHeight = 30 var birthdayLabelY = 10 var spaceBeforeLabels = 10 if surnameLabel.text != nil && surnameLabel.text! != "" { birthdayLabelY = 20 } if userImageView.image != nil { spaceBeforeLabels = 2 * space + imageSize } surnameLabel.frame = CGRect(x: spaceBeforeLabels, y: 0, width: labelWidth, height: labelHeight) nameLabel.frame = CGRect(x: spaceBeforeLabels, y: 40, width: labelWidth, height: labelHeight) userImageView.frame = CGRect(x:space, y: space, width: imageSize, height: imageSize) birthDateLabel.frame = CGRect(x: Int(frame.width) - (labelWidth + space), y: birthdayLabelY, width: labelWidth, height: labelHeight) } } override func sizeThatFits(_ size: CGSize) -> CGSize { return CGSize(width: size.width, height: CGFloat(contentHeight)) } } <file_sep>import UIKit class User: Codable { var name: String? var surname: String var birthDate: String init(surname: String, name: String, birthDate: String) { self.name = name self.birthDate = birthDate self.surname = surname } } <file_sep>// // View.swift // UserInputForm // // Created by User on 08/11/2017. // Copyright © 2017 Studio Mobile. All rights reserved. // class UserCell: UITableViewCell { private let surName = UILabel() private let birthDateLabel = UILabel() private var nameLabel = UILabel() private var isExpanded = false override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(surName) contentView.addSubview(birthDateLabel) contentView.addSubview(nameLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setFields(surname: String, dateOfBirth: String) { surName.text = surname birthDateLabel.text = dateOfBirth } func setFields(surname: String, name: String, dateOfBirth: String) { setFields(surname: surname, dateOfBirth: dateOfBirth) nameLabel.text = name isExpanded = true } override var frame: CGRect { didSet { var birthdayLabelY = 0 surName.frame = CGRect(x: 20, y: 0, width: 150, height: 30) if (isExpanded) { nameLabel.frame = CGRect(x: 20, y: 40, width: 150, height: 30) birthdayLabelY = 20 } birthDateLabel.frame = CGRect(x: frame.width - 170, y: CGFloat(birthdayLabelY), width: 150, height: 30) } } override func sizeThatFits(_ size: CGSize) -> CGSize { if isExpanded { return CGSize(width: size.width, height: size.height + 80) } else { return size } } } <file_sep>// // MainView.swift // UserInputForm // // Created by sm-user on 19.11.2017. // Copyright © 2017 Studio Mobile. All rights reserved. // import UIKit class MainView: UIView { let inputUserView = InputUserView() let userTableView = UITableView() override init(frame: CGRect) { super.init(frame: frame) addSubview(inputUserView) addSubview(userTableView) backgroundColor = .white } func assignActions(userButtonAction: @escaping (UIButton!)->(), takePhotoAction: @escaping (UIButton!)->()) { inputUserView.assignSubmitButtonAction(action: userButtonAction) inputUserView.assignTakePhotoButtonAction(action: takePhotoAction) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var frame: CGRect { didSet { let inputViewHeight = 220 let frameWidth = Int(UIScreen.main.bounds.width) let frameHeight = Int(UIScreen.main.bounds.height) let topBorderDistance = 60 inputUserView.frame = CGRect(x: 0, y: topBorderDistance, width: frameWidth, height: inputViewHeight) userTableView.frame = CGRect(x: 0, y: 280, width: frameWidth, height: frameHeight - (inputViewHeight + topBorderDistance)) } } }
ed44a92fe6f868311bca5f3e7bafc49b92d87e8c
[ "Swift" ]
13
Swift
TretyakovKonstantin/UserInputForm
7daf355e0e18740438bfc05ddce115449425d1cd
251e5f7064bbd1daf7e9bb4fc5e99603d9240a8f
refs/heads/master
<repo_name>deepjafar/Selenium_Concepts<file_sep>/src/com/Selenium/basics/Screenshot_Concept.java package com.Selenium.basics; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class Screenshot_Concept { public static void main(String[] args) throws InterruptedException, IOException { System.setProperty("webdriver.chrome.driver", "C:\\Users\\pachaiappanDe\\eclipse-workspace\\Selenium_Concepts\\Drivers\\chromedriver.exe"); WebDriver driver=new ChromeDriver(); driver.get("https://www.instagram.com/"); Thread.sleep(3000); TakesScreenshot ts=(TakesScreenshot) driver; File srcfile = ts.getScreenshotAs(OutputType.FILE); File desfile = new File("C:\\Users\\pachaiappanDe\\eclipse-workspace\\Selenium_Concepts\\Screenshot\\insta.png"); FileUtils.copyFile(srcfile, desfile); TakesScreenshot ts1=(TakesScreenshot) driver; } } <file_sep>/src/com/Selenium/basics/Alert_Concepts.java package com.Selenium.basics; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class Alert_Concepts { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "C:\\Users\\pachaiappanDe\\eclipse-workspace\\Selenium_Concepts\\Drivers\\chromedriver.exe"); WebDriver driver=new ChromeDriver(); driver.get("http://demo.automationtesting.in/Alerts.html"); driver.manage().window().maximize(); Thread.sleep(3000); WebElement okalert = driver.findElement(By.xpath("(//button[contains(@class,'btn')])[2]")); okalert.click(); Thread.sleep(3000); driver.switchTo().alert().accept(); Thread.sleep(3000); WebElement confirmalert = driver.findElement(By.xpath("//a[contains(text(),' OK & Cancel ')]")); confirmalert.click(); Thread.sleep(3000); WebElement click = driver.findElement(By.xpath("//button[contains(text(),'confirm box ')]")); click.click(); Thread.sleep(3000); driver.switchTo().alert().dismiss(); Thread.sleep(3000); WebElement prompt = driver.findElement(By.xpath("//a[contains(text(),'Alert with Textbox ')]")); prompt.click(); Thread.sleep(3000); WebElement click2 = driver.findElement(By.xpath("//button[contains(@class,'btn btn-info')]")); click2.click(); Thread.sleep(3000); driver.switchTo().alert().sendKeys("Deepika"); driver.switchTo().alert().accept(); } } <file_sep>/src/com/Selenium/basics/Baseclass_browserlan.java package com.Selenium.basics; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class Baseclass_browserlan extends baseclass { public static WebDriver driver; public static void main(String[] args) throws InterruptedException{ driver = getBrowser("chrome"); getUrl("https://www.google.com/"); driver.findElement(By.xpath("//input[@type='text']")).sendKeys("mobile"); } }
6433caf736c0f3c842e47cb48362df9045af55ba
[ "Java" ]
3
Java
deepjafar/Selenium_Concepts
2551c0491555498e21dfc538cb60bc29a37d864c
ddf4a26009b43143001c7ff18ac7d6eef8d097c3
refs/heads/master
<repo_name>katebrighteyes/ros_programming<file_sep>/README.md https://github.com/robotpilot/ros-seminar https://github.com/ROBOTIS-GIT/ros_tutorials ------------------------ ~/catkin_ws$ catkin_make echo "source ~/catkin_ws/devel/setup.bash" >> ~/.bashrc rosrun ros_topic_test topic_pub_test rosrun ros_topic_test topic_sub_test <file_sep>/ros_topic_test/src/topic_pub_test.cpp #include "ros/ros.h" #include "ros_topic_test/MsgTest.h" #include <sstream> int main(int argc, char **argv) { //todo 1 ros::Rate loop_rate(500); ros_topic_test::MsgTest msg; int countnum = 0; while (ros::ok()) { std::stringstream ss; ss << "Hello My Subscriber "; msg.strdata = ss.str(); msg.ndata = countnum; ROS_INFO("send msg = strdata %s %d", msg.strdata.c_str(), msg.ndata); //todo 2 ++countnum; } return 0; } <file_sep>/ros_topic_test/CMakeLists.txt cmake_minimum_required(VERSION 3.0.2) project(ros_topic_test) find_package(catkin REQUIRED COMPONENTS message_generation roscpp std_msgs ) add_message_files(FILES MsgTest.msg) generate_messages(DEPENDENCIES std_msgs) catkin_package( LIBRARIES ros_topic_test CATKIN_DEPENDS roscpp std_msgs ) include_directories(${catkin_INCLUDE_DIRS}) add_executable(topic_pub_test src/topic_pub_test.cpp) add_dependencies(topic_pub_test ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) target_link_libraries(topic_pub_test ${catkin_LIBRARIES}) add_executable(topic_sub_test src/topic_sub_test.cpp) add_dependencies(topic_sub_test ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) target_link_libraries(topic_sub_test ${catkin_LIBRARIES}) <file_sep>/python/test_ros_pkg/src/topic_sub.py #!/usr/bin/env python import rospy from std_msgs.msg import String def callback(msg): print msg.data rospy.init_node('topic_sub') sub = rospy.Subscriber('test_string', String, callback) rospy.spin() <file_sep>/next/darknet_sub/src/darknet_sub_node.cpp #include "ros/ros.h" #include "darknet_ros_msgs/BoundingBoxes.h" #include "darknet_ros_msgs/BoundingBox.h" #include "darknet_sub/MsgState.h" #include <pthread.h> #define RAD2DEG(x) ((x)*180./M_PI) using namespace std; string target = "person"; bool detect_target = false; int state_num = 0; darknet_sub::MsgState msg; ros::Publisher state_pub; void msgCallback(const darknet_ros_msgs::BoundingBoxes::ConstPtr& msg) { } #if 1 void *test(void *data) { } #endif int main(int argc, char **argv) { cout<<"darknet_sub_node" <<endl; #if 1 pthread_t thread_t; int status; ros::init(argc, argv, "darknet_sub_node"); ros::NodeHandle nh; ros::Subscriber obj_sub = nh.subscribe("/darknet_ros/bounding_boxes",100,msgCallback); state_pub = nh.advertise<darknet_sub::MsgState>("cur_state", 100); if (pthread_create(&thread_t, NULL, test, 0) < 0) { printf("thread create error:"); exit(0); } ros::spin(); pthread_join(thread_t, (void **)&status); printf("Thread End %d\n", status); #endif return 0; } <file_sep>/ros_topic_test/src/topic_sub_test.cpp #include "ros/ros.h" #include "ros_topic_test/MsgTest.h" //todo 1 int main(int argc, char **argv) { ros::init(argc, argv, "topic_sub_test"); ros::NodeHandle nh; //todo 2 return 0; } <file_sep>/next2/readme.txt cd sudo apt-get install ros-melodic-image-transport ros-melodic-vision-msgs ./install_catkinws.sh dnn_ws cd dnn_ws/src git clone https://github.com/dusty-nv/ros_deep_learning cd .. catkin_make source devel/setup.bash echo "source ~/dnn_ws/devel/setup.bash" >> ~/.bashrc # VIEWER roslaunch ros_deep_learning video_viewer.ros1.launch input:=/dev/video1 output:=display://0 # detection roslaunch ros_deep_learning detectnet.ros1.launch input:=/dev/video1 output:=display://0 <file_sep>/next/darknet_sub/CMakeLists.txt cmake_minimum_required(VERSION 2.8.3) project(darknet_sub) ## Compile as C++11, supported in ROS Kinetic and newer # add_compile_options(-std=c++11) find_package(catkin REQUIRED COMPONENTS message_generation roscpp std_msgs std_msgs darknet_ros darknet_ros_msgs sensor_msgs ) add_message_files(FILES MsgState.msg) generate_messages(DEPENDENCIES std_msgs) ################################### ## catkin specific configuration ## ################################### catkin_package( LIBRARIES acc_logic_ros CATKIN_DEPENDS roscpp std_msgs darknet_ros darknet_ros_msgs sensor_msgs ) ########### ## Build ## ########### link_directories( /usr/local/cuda/lib64 ) include_directories( include ${catkin_INCLUDE_DIRS} ${RPLIDAR_SDK_PATH}/include ${RPLIDAR_SDK_PATH}/src ) add_executable(darknet_sub_node src/darknet_sub_node.cpp) add_dependencies(darknet_sub_node ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) target_link_libraries(darknet_sub_node cuda cudart cublas pthread ${catkin_LIBRARIES} ) <file_sep>/python/test_ros_pkg/src/topic_pub.py #!/usr/bin/env python import rospy from std_msgs.msg import String rospy.init_node('topic_pub') pub= rospy.Publisher('test_string', String) rate = rospy.Rate(2) while not rospy.is_shutdown(): pub.publish('AAAAAA') rate.sleep()
f2e0828693be4839e66dc8e076d6d258a2253942
[ "CMake", "Markdown", "Python", "Text", "C++" ]
9
Markdown
katebrighteyes/ros_programming
9a8e4d34965f640c4cdf80e6713ba30331102976
c7aa40b85b37cf19b0e3abc6eafb9e49d7df97a2
refs/heads/master
<repo_name>EternalReturnStudio/temperature<file_sep>/modules/buttons.lua button = { play = { name = "play", x = 0, y = 0, width = 0, height = 0, up = nil, down = nil, wasDown = false, isDown = false, justPressed = false }, exit = { name = "exit", x = 0, y = 0, width = 0, height = 0, up = nil, down = nil, wasDown = false, isDown = false, justPressed = false } } function drawButton(b) if (b.isDown) then love.graphics.draw(b.down, b.x * settings.hScale, b.y * settings.vScale, 0, settings.hScale, settings.vScale) else love.graphics.draw(b.up, b.x * settings.hScale, b.y * settings.vScale, 0, settings.hScale, settings.vScale) end end function buttonPressed(x, y, b) if global.inGame then if b == 1 then if not timers.toMenu and boxHit(x, y, button.back.x * settings.hScale, button.back.y * settings.vScale, button.back.width * settings.hScale, button.back.height * settings.vScale) then button.back.isDown = true end end elseif global.inCredits then if b == 1 then if not timers.toMenu and boxHit(x, y, button.back.x * settings.hScale, button.back.y * settings.vScale, button.back.width * settings.hScale, button.back.height * settings.vScale) then button.back.isDown = true end end else if b == 1 then if not timers.toGame and boxHit(x, y, button.play.x * settings.hScale, button.play.y * settings.vScale, button.play.width * settings.hScale, button.play.height * settings.vScale) then button.play.isDown = true res.sfx.select_0:play() end -- if not timers.toCredits and boxHit(x, y, button.info.x * settings.hScale, button.info.y * settings.vScale, button.info.width * settings.hScale, button.info.height * settings.vScale) then -- button.info.isDown = true -- end -- if not timers.exit and boxHit(x, y, button.exit.x * settings.hScale, button.exit.y * settings.vScale, button.exit.width * settings.hScale, button.exit.height * settings.vScale) then -- button.exit.isDown = true -- end end end end function buttonReleased(x, y, b) if global.inGame then if b == 1 then if not timers.toMenu and button.back.isDown then button.back.isDown = false end if not timers.reset and button.again.isDown then button.again.isDown = false end end elseif global.inCredits then if b == 1 then if not timers.toMenu and button.back.isDown then button.back.isDown = false end end else if b == 1 then if not timers.toGame and button.play.isDown then button.play.isDown = false end -- if not timers.toCredits and button.info.isDown then button.info.isDown = false end -- if not timers.exit and button.exit.isDown then button.exit.isDown = false end end end end <file_sep>/modules/window.lua function setupWindow() love.window.setMode(0, 0, { fullscreen = false }) global.screenWidth = love.graphics.getWidth() global.screenHeight = love.graphics.getHeight() if global.scaledFullscreen then -- NOTE: posible escalado entero while global.width * (global.hFullscreenScale + 1) < global.screenWidth and global.height * (global.vFullscreenScale + 1) < global.screenHeight do global.hFullscreenScale = global.hFullscreenScale + 1 global.vFullscreenScale = global.vFullscreenScale + 1 end else global.hFullscreenScale = global.screenWidth / global.width global.vFullscreenScale = global.screenHeight / global.height end love.graphics.setBackgroundColor(88, 88, 88) if settings.fullscreen then global.hScaleBefore = settings.hScale global.vScaleBefore = settings.vScale settings.hScale = global.hFullscreenScale settings.vScale = global.vFullscreenScale end love.window.setMode(global.width * settings.hScale, global.height * settings.vScale, { fullscreen = settings.fullscreen, borderless = global.borderless }) love.graphics.setDefaultFilter("nearest", "nearest", 0) end function scaleUpWindow() if not settings.fullscreen and settings.hScale < 5 and settings.vScale < 5 then settings.hScale = settings.hScale + 1 settings.vScale = settings.vScale + 1 love.window.setMode(global.width * settings.hScale, global.height * settings.vScale, { fullscreen = settings.fullscreen, borderless = global.borderless }) end end function scaleDownWindow() if not settings.fullscreen and settings.hScale > 1 and settings.vScale > 1 then settings.hScale = settings.hScale - 1 settings.vScale = settings.vScale - 1 love.window.setMode(global.width * settings.hScale, global.height * settings.vScale, { fullscreen = settings.fullscreen, borderless = global.borderless }) end end function toggleFullscreen() settings.fullscreen = not settings.fullscreen if settings.fullscreen then global.hScaleBefore = settings.hScale global.vScaleBefore = settings.vScale settings.hScale = global.hFullscreenScale settings.vScale = global.vFullscreenScale else settings.hScale = global.hScaleBefore settings.vScale = global.vScaleBefore end love.window.setMode(global.width * settings.hScale, global.height * settings.vScale, { fullscreen = settings.fullscreen, borderless = global.borderless }) end function storeWindowScale() if settings.fullscreen then settings.hScale = global.hScaleBefore settings.vScale = global.vScaleBefore end end <file_sep>/scenes/game.lua function updateGame(dt) button.back.justPressed = false if button.back.wasDown and not button.back.isDown then button.back.isDown = false button.back.wasDown = false button.back.justPressed = true timers.inTransition = true timers.toMenu = true startTransition() end button.back.wasDown = button.back.isDown if button.back.justPressed then res.sfx.select_1:play() end end function drawGame(dt) love.graphics.draw(res.img.game, 0, 0, 0, settings.hScale, settings.vScale) drawPaths(dt) love.graphics.draw(res.img.board, 0, 0, 0, settings.hScale, settings.vScale) drawMoves(dt) drawTokens(dt) if button.back.isDown then love.graphics.draw(button.back.down, button.back.x * settings.hScale, button.back.y * settings.vScale, 0, settings.hScale, settings.vScale) else love.graphics.draw(button.back.up, button.back.x * settings.hScale, button.back.y * settings.vScale, 0, settings.hScale, settings.vScale) end if button.again.isDown then love.graphics.draw(button.again.down, button.again.x * settings.hScale, button.again.y * settings.vScale, 0, settings.hScale, settings.vScale) else love.graphics.draw(button.again.up, button.again.x * settings.hScale, button.again.y * settings.vScale, 0, settings.hScale, settings.vScale) end love.graphics.setColor(68, 68, 68, 255) love.graphics.print("Level " .. settings.level, (57 - (res.fnt.font:getWidth("Level " .. settings.level) / 2)) * settings.hScale, (global.height * 3 / 5) * settings.vScale, 0, settings.hScale, settings.vScale) love.graphics.setColor(255, 255, 255, 255) end function DEPRECATED_nextLevel() love.filesystem.write("data.bin", table.show(settings, "settings")) res.sfx.yaay:setVolume(0.5) res.sfx.yaay:play() end <file_sep>/scenes/credits.lua function updateCredits(dt) button.back.justPressed = false if button.back.wasDown and not button.back.isDown then button.back.isDown = false button.back.wasDown = false button.back.justPressed = true timers.inTransition = true timers.toMenu = true startTransition() end button.back.wasDown = button.back.isDown if button.back.justPressed then res.sfx.select_1:play() end end function drawCredits(dt) love.graphics.draw(res.img.credits, 0, 0, 0, settings.hScale, settings.vScale) if button.back.isDown then love.graphics.draw(button.back.down, button.back.x * settings.hScale, button.back.y * settings.vScale, 0, settings.hScale, settings.vScale) else love.graphics.draw(button.back.up, button.back.x * settings.hScale, button.back.y * settings.vScale, 0, settings.hScale, settings.vScale) end end <file_sep>/scenes/menu.lua num = 25 frames = 180 theta = 0 function updateMenu(dt) button.play.justPressed = false if button.play.wasDown and not button.play.isDown then button.play.isDown = false button.play.wasDown = false button.play.justPressed = true timers.inTransition = true timers.toGame = true startTransition() end button.play.wasDown = button.play.isDown button.exit.justPressed = false if button.exit.wasDown and not button.exit.isDown then button.exit.isDown = false button.exit.wasDown = false button.exit.justPressed = true timers.inTransition = true timers.exit = true exitTransition() end button.exit.wasDown = button.exit.isDown if button.play.justPressed then res.sfx.select_2:play() end if button.exit.justPressed then res.sfx.select_0:play() end end function drawMenu(dt) love.graphics.draw(res.img.menu, 0, 0, 0, settings.hScale, settings.vScale) local hUnit = love.graphics.getWidth() / num local vUnit = love.graphics.getHeight() / num for y=0,num do for x=0,num do local distance = math.sqrt(math.pow((love.graphics.getWidth() / 2) - (x * hUnit), 2) + math.pow((love.graphics.getHeight() / 2) - (y * vUnit), 2)) local offset = map(distance, 0, math.sqrt(math.pow(love.graphics.getWidth() / 2, 2) + math.pow(love.graphics.getHeight() / 2, 2)), 0, math.pi * 2) local sz = map(math.sin(theta + offset), -1, 1, hUnit * 0.2, vUnit * 0.1) local angle = math.atan2(y * vUnit - love.graphics.getHeight() / 2, x * hUnit - love.graphics.getWidth() / 2) love.graphics.push() love.graphics.translate(x * hUnit, y * vUnit) love.graphics.rotate(angle) love.graphics.ellipse("fill", map(math.sin(theta + offset), -1, 1, 0, 50), 0, sz / 2, sz / 2) love.graphics.pop() end end theta = theta - (math.pi * 2 / frames) drawButton(button.play) end <file_sep>/modules/resources.lua res = { dir = "assets/", imgQueue = {}, bgmQueue = {}, sfxQueue = {}, fntQueue = {}, img = {}, bgm = {}, sfx = {}, fnt = {} } function loadFont(name, src, size) res.fntQueue[name] = { src, size } end function loadImg(name, src) res.imgQueue[name] = src end function loadBgm(name, src) res.bgmQueue[name] = src end function loadSfx(name, src) res.sfxQueue[name] = src end function loadRes(threaded) for name, pair in pairs(res.fntQueue) do res.fnt[name] = love.graphics.newFont(res.dir .. "fnt/" .. pair[1], pair[2]) res.fntQueue[name] = nil end for name, src in pairs(res.imgQueue) do res.img[name] = love.graphics.newImage(res.dir .. "img/" .. src) res.imgQueue[name] = nil end for name, src in pairs(res.bgmQueue) do res.bgm[name] = love.audio.newSource(res.dir .. "bgm/" .. src) res.bgm[name]:setLooping(true) res.bgmQueue[name] = nil end for name, src in pairs(res.sfxQueue) do res.sfx[name] = love.audio.newSource(res.dir .. "sfx/" .. src) res.sfx[name]:setLooping(false) res.sfxQueue[name] = nil end end <file_sep>/modules/transitions.lua transition = { red = 32, green = 32, blue = 32, alpha = 0 } timers = { time = 1.0, inTransition = false, toGame = false, toMenu = false, toCredits = false, exit = false, toGameTime = 0, toMenuTime = 0, toCreditsTime = 0, exitTime = 0 } function startTransition() flux.to(transition, 0.5, { alpha = 255 }):after(transition, 0.5, { alpha = 0 }) end function exitTransition() flux.to(global, 1, { volume = 0 }) flux.to(transition, 1, { red = 0, green = 0, blue = 0, alpha = 255 }) end function drawTransition() love.graphics.setColor(transition.red, transition.green, transition.blue, transition.alpha) love.graphics.rectangle("fill", 0, 0, global.width * settings.hScale, global.height * settings.vScale) love.graphics.setColor(255, 255, 255, 255) end function updateTimers(dt) if timers.exit then res.bgm.music:setVolume(global.volume) timers.exitTime = timers.exitTime + dt if timers.exitTime > timers.time then timers.exitTime = 0 timers.exit = false timers.inTransition = false love.event.push("quit") end elseif timers.toGame then timers.toGameTime = timers.toGameTime + dt if timers.toGameTime > timers.time / 2 then global.inGame = true end if timers.toGameTime > timers.time then timers.toGameTime = 0 timers.toGame = false timers.inTransition = false resetLevel() timers.resetting = true resetTransition() end elseif timers.toMenu then timers.toMenuTime = timers.toMenuTime + dt if timers.toMenuTime > timers.time / 2 then global.inGame = false global.inCredits = false end if timers.toMenuTime > timers.time then timers.toMenuTime = 0 timers.toMenu = false timers.inTransition = false end elseif timers.toCredits then timers.toCreditsTime = timers.toCreditsTime + dt if timers.toCreditsTime > timers.time / 2 then global.inCredits = true end if timers.toCreditsTime > timers.time then timers.toCreditsTime = 0 timers.toCredits = false timers.inTransition = false end end end function DEPRECATED_resetTransition() for i, token in ipairs(tokens) do flux.to(token, 1, { x = spots[token.pos].x, y = spots[token.pos].y }):ease(global.easing) end end <file_sep>/README.md # Temperature Multiplayer game made with Love2D <file_sep>/main.lua -- require("lib/lovedebug") flux = require("lib/flux") require("modules/resources") require("modules/utils") require("modules/transitions") require("modules/window") require("modules/buttons") require("scenes/menu") require("scenes/game") require("scenes/credits") -- ============================================================= -- Variables global = { debug = true, borderless = false, width = 640, height = 360, screenWidth = 0, screenHeight = 0, hFullscreenScale = 1, vFullscreenScale = 1, scaledFullscreen = false, hScaleBefore = 1, vScaleBefore = 1, volume = 1, inGame = false, inCredits = false, easing = "backout" } settings = { hScale = 1, vScale = 1, fullscreen = false, sound = true } -- ============================================================= -- Love2D main functions function love.load() -- load settings if not love.filesystem.exists("data.bin") then love.filesystem.write("data.bin", table.show(settings, "settings")) end settingsChunk = love.filesystem.load("data.bin") settingsChunk() setupWindow() math.randomseed(os.time()) -- load resources loadImg("menu", "menu.png") loadImg("credits", "credits.png") loadImg("game", "game.png") loadImg("btnPlayUp", "btn-play-up.png") loadImg("btnPlayDown", "btn-play-down.png") loadSfx("select_0", "select_0.ogg") loadSfx("select_1", "select_1.ogg") loadSfx("select_2", "select_2.ogg") loadSfx("select_3", "select_3.ogg") loadBgm("music", "music.mp3") loadSfx("yaay", "yaay.ogg") loadFont("font", "smart.ttf", 32) loadRes() -- setup objects -- button.play.up = res.img.playUp -- button.play.down = res.img.playDown -- button.play.width = button.play.up:getWidth() -- button.play.height = button.play.up:getHeight() -- button.play.x = global.width / 2 - (button.play.up:getWidth() / 2) -- button.play.y = global.height * 3 / 4 - (button.play.down:getHeight() / 2) - 10 -- button.exit.up = res.img.exitUp -- button.exit.down = res.img.exitDown -- button.exit.width = button.exit.up:getWidth() -- button.exit.height = button.exit.up:getHeight() button.play.up = res.img.btnPlayUp button.play.down = res.img.btnPlayDown button.play.width = button.play.up:getWidth() button.play.height = button.play.up:getHeight() button.play.x = 32 button.play.y = 280 love.graphics.setFont(res.fnt.font) if settings.sound then res.bgm.music:play() end end -- ------------------------------------------------------------- function love.update(dt) flux.update(dt) if not timers.inTransition then if global.inGame then updateGame(dt) elseif global.inCredits then updateCredits(dt) else updateMenu(dt) end end updateTimers(dt) end -- ------------------------------------------------------------- function love.draw(dt) if global.inGame then drawGame(dt) elseif global.inCredits then drawCredits(dt) else drawMenu(dt) end if timers.inTransition then drawTransition() end if global.debug then local yy = 5 love.graphics.setColor(255, 255, 255, 255) love.graphics.print("::Debug::", 5, yy) yy = yy + 25 love.graphics.print("FPS: " .. love.timer.getFPS(), 5, yy) yy = yy + 25 love.graphics.print("play.isDown: " .. tostring(button.play.isDown), 5, yy) yy = yy + 25 love.graphics.print("mouse on button: " .. tostring(boxHit(love.mouse.getX(), love.mouse.getY(), button.play.x * settings.hScale, button.play.y * settings.vScale, button.play.width * settings.hScale, button.play.height * settings.vScale)), 5, yy) end end -- ------------------------------------------------------------- function love.keypressed(k) if not timers.inTransition then if k == "+" then scaleUpWindow() return end if k == "-" then scaleDownWindow() return end if k == "return" and love.keyboard.isDown("lalt", "ralt", "alt") then toggleFullscreen() return end end end -- ------------------------------------------------------------- function love.keyreleased(k) if not timers.toGame and not timers.toMenu then -- quit the game if k == "escape" then if global.inGame or global.inCredits then timers.inTransition = true timers.toMenu = true startTransition() res.sfx.select_1:play() else res.sfx.select_0:play() timers.inTransition = true timers.exit = true exitTransition() end return end end end -- ------------------------------------------------------------- function love.mousepressed(x, y, b) buttonPressed(x, y, b) end -- ------------------------------------------------------------- function love.mousereleased(x, y, b) buttonReleased(x, y, b) end -- ------------------------------------------------------------- function love.mousemoved(x, y, dx, dy) end -- ------------------------------------------------------------- function love.quit() storeWindowScale() love.filesystem.write("data.bin", table.show(settings, "settings")) end
d3db72d40dbeab8891482b347883d02120adb258
[ "Markdown", "Lua" ]
9
Lua
EternalReturnStudio/temperature
6e59f1c6a89730f1ddb67200e4f9159207e98901
f5a360d9b7f6b1996c6d8100a9b1daa23026e130
refs/heads/master
<repo_name>pseudopresence/exocortex<file_sep>/fs/fs.js // CouchDB for metadata // Git blobs for file contents // Access through HTTP // Not in a runnable state! Just some pasted code. // Git: var gitteh = require("gitteh"), path = require("path"), fs = require("fs"); var repository = gitteh.openRepository(path.join(__dirname, "..", ".git")); var blob = repository.getBlob(sha1); // HTTP: var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(1337, "127.0.0.1"); console.log('Server running at http://127.0.0.1:1337/'); // CouchDB: var couchdb = require("couchdb-api"); // connect to a couchdb server (defaults to localhost:5984) var server = couchdb.srv(); // test it out! server.info(function (err, response) { console.log(response); // should get `{ couchdb: "Welcome", version: "1.0.1" } // if something went wrong, the `err` argument would provide the error that CouchDB provides }); // select a database var db = server.db("my-database"); db.info(function (err, response) { console.log(response); // should see the basic statistics for your test database // if you chose a non-existant db, you'd get { error: "not_found", reason: "no_db_file" } in place of `err` });
ed0ddf282f68b304d29781e935605813429c7407
[ "JavaScript" ]
1
JavaScript
pseudopresence/exocortex
b964f940c7123cdac16105a5a32dd5ac4d2f10a2
78562cc72f9dca6487901174bea32dd314f21ff4
refs/heads/master
<file_sep><?php $err_message=""; if($_SERVER["REQUEST_METHOD"] == "POST"){ $username=$_POST["username"]; $password=$_POST["<PASSWORD>"]; if($username == "asif" && $password == "<PASSWORD>"){ setcookie("username",$username,time()+120); header("Location:dashboard.php"); } else $err_message= "Invalid Username or Password"; } ?> <html> <head> </head> <body> <form action="" method="post"> <table align="center"> <tr> <td><span color="red"><?php echo $err_message;?></span> </td> </tr> <tr> <td><span>Username:</span> </td> <td><input type="text" name="username"></td> </tr> <tr> <td><span>Password: </span></td> <td><input type="password" name="password"></td> </tr> <tr> <td colspan="2" align="right"><input type="submit" value="Login" name="login"> </tr> </table> </form> </body> </html><file_sep><?php $uname=""; $pass=""; if($_SERVER["REQUEST_METHOD"] == "POST"){ $uname=$_POST["uname"]; $pass=$_POST["pass"]; $server="localhost"; $user="root"; $password=""; $db="mydatabase"; $conn = mysqli_connect($server,$user,$password,$db); $query= "insert into users values(NULL,'$uname','$pass','user')"; if(mysqli_query($conn,$query)){ echo "User inserted"; } else{ echo "Can not insert user"; } } ?> <html> <head> </head> <body> <form action="" method="post"> <table align="center"> <tr> <td><span>Username:</span> </td> <td><input type="text" name="uname"></td> </tr> <tr> <td><span>Password: </span></td> <td><input type="password" name="pass"></td> </tr> <tr> <td colspan="2" align="right"><input type="submit" value="Register" name="login"> <a href="login.php"> Login </a> </tr> </table> </form> </body> </html>
e142d940d215d82a030fe1a7f4b50208997f897b
[ "PHP" ]
2
PHP
EvanSarwer/WT_Sp21_Final
2ba9533c30d83cd5615c9d4353d8a647269685b7
a4c758d0338d13bdd8fbcce2f8b15b982bf30e28
refs/heads/master
<file_sep>ChatterBot==1.0.0 chatterbot-corpus==1.2.0 click==7.1.2 Flask==1.1.2 itsdangerous==1.1.0 Jinja2==2.11.2 joblib==1.0.0 MarkupSafe==1.1.1 mathparse==0.1.2 nltk==3.5 packaging==20.8 Pint==0.16.1 pymongo==3.11.2 pyparsing==2.4.7 python-dateutil==2.7.5 pytz==2020.5 PyYAML==3.13 regex==2020.11.13 six==1.15.0 SQLAlchemy==1.2.19 tqdm==4.56.0 Werkzeug==1.0.1 <file_sep>#import files from flask import Flask, render_template, request from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer app = Flask(__name__) bot = ChatBot("Candice") trainer = ChatterBotCorpusTrainer(bot) # trainer.train({'What is your name?':'My name is Candice'}) #trainer.train("chatterbot.corpus.english") trainer.train("data/greetings.yml") trainer.train("data/data.yml") @app.route("/chatbot") def home(): return render_template("home.html") @app.route("/get") def get_bot_response(): userText = request.args.get('msg') return str(bot.get_response(userText)) if __name__ == "__main__": app.run()
f5f77aa81e76aac5e086f8caf030c725d0634f6d
[ "Python", "Text" ]
2
Text
Adam-Banderker/ChatBot
651034266e8fe9a20d1a722333ccfadc83658cc5
df27f89aa3dd886fe6f28bbb5518ab2c22b68457
refs/heads/main
<repo_name>junckim/minishell<file_sep>/workspace/libs/libft/Makefile NAME = libft.a CC = gcc FLAGS = -Werror -Wextra -Wall SRCS = ft_atoi.c ft_bzero.c ft_calloc.c ft_isalnum.c ft_isalpha.c ft_isascii.c ft_isdigit.c ft_isprint.c ft_memccpy.c ft_memchr.c ft_memcmp.c ft_memcpy.c ft_memmove.c ft_memset.c ft_strchr.c ft_strdup.c ft_strlcat.c ft_strlcpy.c ft_strlen.c ft_strncmp.c ft_strnstr.c ft_strrchr.c ft_tolower.c ft_toupper.c ft_itoa.c ft_putchar_fd.c ft_putstr_fd.c ft_putendl_fd.c ft_putnbr_fd.c ft_split.c ft_strjoin.c ft_strmapi.c ft_strtrim.c ft_substr.c OBJS = $(SRCS:.c=.o) BONUS = ft_lstnew.c ft_lstadd_front.c ft_lstsize.c ft_lstlast.c ft_lstadd_back.c ft_lstdelone.c ft_lstclear.c ft_lstiter.c ft_lstmap.c OBJSBONUS = $(BONUS:.c=.o) .PHONY : all clean fclean re bonus all : $(NAME) $(NAME) : $(OBJS) @ar rc $(NAME) $(OBJS) @ranlib $(NAME) @echo -------------make success libft.a------------- .c.o : @$(CC) $(FLAGS) -c $< clean : @rm -f $(OBJS) $(OBJSBONUS) fclean : clean @rm -f $(NAME) re : fclean all bonus : $(OBJS) $(OBJSBONUS) @ar rc $(NAME) $(OBJS) $(OBJSBONUS) @ranlib $(NAME) @echo ---------------make libft bonus--------------- <file_sep>/workspace/srcs/word_init.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* word_init.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: junkang <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/14 19:35:51 by junkang #+# #+# */ /* Updated: 2021/01/14 19:40:16 by junkang ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/minishell.h" void word_init(t_word_block *word) { word->quotation = -1; word->word = ft_strdup(""); word->is_conti = -1; word->sep = -1; } static int ft_cnt_minus(const char *s) { int ret; ret = 0; while (*s) { if (*s == -1) ret++; s++; } return (ret); } static char *ft_except_strdup(const char *s) { size_t len; char *res; char *temp; len = ft_strlen(s) - ft_cnt_minus(s); if ((res = (char *)malloc(sizeof(char) * (len + 1))) == NULL) return (NULL); temp = res; while (*s) { if (*s == -1) { s++; continue ; } *temp++ = *s++; } *temp = 0; return (res); } void word_join(t_word_block *dest, t_word_block *srcs) { char *tmp; if (!dest->word) dest->word = ft_strdup(""); tmp = srcs->word; srcs->word = ft_except_strdup(srcs->word); free(tmp); tmp = dest->word; dest->word = ft_strjoin(dest->word, srcs->word); free(tmp); dest->quotation = srcs->quotation; dest->is_conti = srcs->is_conti; dest->sep = srcs->sep; word_free(srcs); } void word_free(t_word_block *word) { word->quotation = -1; free(word->word); word->word = NULL; word->is_conti = -1; word->sep = -1; } <file_sep>/workspace/srcs/change_env.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* change_env.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: junkang <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/14 19:38:27 by junkang #+# #+# */ /* Updated: 2021/01/14 19:38:28 by junkang ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/minishell.h" extern int g_error_status; static int isvalid_env_mark(char *word, int idx) { if (idx > 0 && word[idx - 1] == -1) return (0); return (1); } static int change_basic(char **word, int idx, t_env *env) { int j; char c; char *key; char *val; int flag; flag = 0; j = end_env_index(*word, idx); c = (*word)[j]; (*word)[j] = 0; key = ft_strdup(&((*word)[idx + 1])); (*word)[j] = c; if ((val = get_value(env, key)) == NULL) { flag = 1; val = ft_strdup(""); } free(key); idx = env_strdup(word, idx, j, val); if (flag == 1) free(val); return (idx); } static int change_return(char **word, int idx) { int j; char c; char *key; char *val; j = idx + 2; c = (*word)[j]; (*word)[j] = 0; key = ft_strdup(&((*word)[idx + 1])); (*word)[j] = c; if ((val = ft_itoa(g_error_status)) == NULL) val = ft_strdup(""); free(key); idx = env_strdup(word, idx, j, val); free(val); return (idx); } static int change_bracelet(char **word, int idx, t_env *env) { int j; char c; char *key; char *val; int flag; flag = 0; j = end_env_bracelet(*word, idx); c = (*word)[j]; (*word)[j] = 0; key = ft_strdup(&((*word)[idx + 2])); (*word)[j] = c; if ((val = get_value(env, key)) == NULL) { flag = 1; val = ft_strdup(""); } free(key); idx = env_strdup(word, idx, j + 1, val); if (flag == 1) free(val); return (idx); } void change_env(t_word_block *word, t_env *env) { int i; i = -1; while ((word->word)[++i]) { if ((word->word)[i] == '$' && (word->word)[i + 1] == '?') i = change_return(&(word->word), i); else if ((word->word)[i] == '$' && (word->word)[i + 1] == '{') i = change_bracelet(&(word->word), i, env); else if ((word->word)[i] == '$' && isvalid_env_mark(word->word, i)) i = change_basic(&(word->word), i, env); } } <file_sep>/workspace/srcs/list_check.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* list_check.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: joockim <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/12 14:21:59 by joockim #+# #+# */ /* Updated: 2021/01/14 19:39:46 by junkang ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/minishell.h" int node_check(t_commands *lst) { if (lst->str->redir == -1 && ft_strlen(lst->str->word) == 0) { if (lst->sep == PIPE) return (ERR_EMPTY_PIPE); else if (lst->sep == SEMI) return (ERR_EMPTY_SEMI); else return (ERR_EMPTY_NEWLINE); } return (1); } int pipe_check(t_commands *pipe_lst) { while (pipe_lst) { if (pipe_lst->str->redir == -1 && ft_strlen(pipe_lst->str->word) == 0) { if (pipe_lst->sep == PIPE) return (ERR_EMPTY_PIPE); else if (pipe_lst->sep == SEMI) return (ERR_EMPTY_SEMI); else return (ERR_EMPTY_NEWLINE); } pipe_lst = pipe_lst->pipe; } return (1); } int list_check(t_commands *lst) { int ret; while (lst) { if ((ret = node_check(lst)) != 1) return (ret); if (lst->pipe) { if ((ret = pipe_check(lst->pipe)) != 1) return (ret); } lst = lst->next; } return (1); } <file_sep>/workspace/srcs/work_cmd.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* work_cmd.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: joockim <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/15 18:42:38 by joockim #+# #+# */ /* Updated: 2021/01/15 18:47:50 by joockim ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/minishell.h" extern char *g_read_str; extern int g_error_status; int status_return(int status) { if (ft_ifsignal(status)) return (128 + status); if (ft_exitstatus(status) != 255) return (ft_exitstatus(status)); return (255); } int path_work(t_commands *node, char *path, t_env *env) { int pid; char **argv; char **envp; int status; int res; if ((pid = fork()) == -1) return (-2); else if (pid == 0) { argv = str_to_argv(node); envp = env_to_envp(env); if (node->fdflag == 1) dup2(node->fd, STDOUT_FILENO); else if (node->fdflag == 2) dup2(node->fd, STDIN_FILENO); res = execve(path, argv, envp); exit(res); } else { waitpid(pid, &status, 0); } return (status_return(status)); } int excute_work(t_commands *node, t_env *env) { char *path; path = node->str->word; return (path_work(node, path, env)); } int path_excute(t_commands *node, t_env *env, t_path *path) { int res; char *word; char *tmp; word = ft_strdup(node->str->word); while (path) { tmp = triple_join(path->path, "/", word); free(node->str->word); node->str->word = tmp; if ((res = excute_work(node, env)) != 255) { free(word); word = NULL; return (res); } path = path->next; } free(word); word = NULL; return (127); } void work_command(t_commands *node, t_env **env) { t_path *path; int cmd; path = make_path_lst(*env); if (work_redir(node) == SYS_SYNTAX) { g_error_status = SYS_SYNTAX; free_path(&path); return ; } if (node->str->word[0] == '/') { if (excute_work(node, *env) == 255) g_error_status = 127; } else { if ((cmd = is_command(node->str->word)) == -1) g_error_status = path_excute(node, *env, path); else g_error_status = command_work(node, env, cmd); } if (g_error_status == 127) error_check(SYS_CMD_NOT_FOUND, ft_strrchr(node->str->word, '/') + 1); free_path(&path); } <file_sep>/workspace/srcs/env_func_2.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* env_func_2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: joockim <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/15 17:32:46 by joockim #+# #+# */ /* Updated: 2021/01/15 17:54:15 by joockim ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/minishell.h" t_env *envp_to_env(char *envp) { t_env *env; char *path; char *key; char *value; path = ft_strchr(envp, '='); key = envp; value = path + 1; *path = 0; if ((env = malloc(sizeof(t_env))) == 0) return (0); env->key = ft_strdup(key); env->value = ft_strdup(value); env->next = NULL; return (env); } void add_envlst(t_env *env, char *envp) { t_env *elem; elem = envp_to_env(envp); while (env->next) env = env->next; env->next = elem; } t_env *make_envlst(char **envp) { t_env *env; env = envp_to_env(*envp); envp++; while (*envp) { add_envlst(env, *envp); envp++; } return (env); } char *get_value(t_env *env, char *key) { char *value; value = NULL; while (env) { if (!ft_strncmp(key, env->key, ft_strlen(key)) && !ft_strncmp(key, env->key, ft_strlen(env->key))) value = env->value; env = env->next; } return (value); } <file_sep>/workspace/include/minishell.h /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* minishell.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kimjoochan <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/12/10 15:12:06 by kimjoocha #+# #+# */ /* Updated: 2021/01/15 19:01:26 by joockim ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef MINISHELL_H # define MINISHELL_H # include <unistd.h> # include <sys/wait.h> # include <signal.h> # include <sys/stat.h> # include <dirent.h> # include <errno.h> # include <string.h> # include <fcntl.h> # include "../libs/libft/libft.h" # include "../libs/libftprintf/include/ft_printf.h" # include <stdio.h> # define SEMI 1 # define PIPE 2 # define REDIR 3 # define REV_REDIR 4 # define D_REDIR 5 # define SPACE 6 # define BQU 1 # define SQU 2 # define BSL 3 # define ECHO 1 # define CD 2 # define PWD 3 # define EXPORT 4 # define UNSET 5 # define ENV 6 # define LS 7 # define EXIT 8 # define ERR_EXPORT -2 # define ERR_EMPTY_SEMI -3 # define ERR_EMPTY_SEMI_S "syntax error near unexpected token `;'" # define ERR_EMPTY_PIPE -4 # define ERR_EMPTY_PIPE_S "syntax error near unexpected token `|'" # define ERR_EMPTY_REDIR -5 # define ERR_EMPTY_REDIR_S "syntax error near unexpected token `>'" # define ERR_EMPTY_D_REDIR -6 # define ERR_EMPTY_D_REDIR_S "syntax error near unexpected token `>>'" # define ERR_EMPTY_REV_REDIR -7 # define ERR_EMPTY_REV_REDIR_S "syntax error near unexpected token `<'" # define ERR_EMPTY_NEWLINE -8 # define ERR_EMPTY_NEWLINE_S "syntax error near unexpected token `newline'" # define ERR_NO_SUCH_FILE -9 # define SYS_CMD_NOT_FOUND 127 # define SYS_SYNTAX 258 # define COLOR_RED "\x1b[31m" # define COLOR_GREEN "\x1b[32m" # define COLOR_YELLOW "\x1b[33m" # define COLOR_BLUE "\x1b[34m" # define COLOR_MAGENTA "\x1b[35m" # define COLOR_CYAN "\x1b[36m" # define COLOR_WHITE "\x1b[37m" # define COLOR_BRED "\x1b[91m" # define COLOR_BGREEN "\x1b[92m" # define COLOR_BYELLOW "\x1b[93m" # define COLOR_BBLUE "\x1b[94m" # define COLOR_BMAGENTA "\x1b[95m" # define COLOR_BCYAN "\x1b[96m" # define COLOR_BWHITE "\x1b[97m" # define COLOR_RESET "\x1b[0m" typedef struct s_path { char *path; struct s_path *next; } t_path; typedef struct s_env { char *key; char *value; struct s_env *next; } t_env; typedef struct s_str { int redir; char *word; struct s_str *next; } t_str; typedef struct s_commands { int sep; int command; t_str *str; int fd; int fdflag; struct s_commands *pipe; struct s_commands *next; } t_commands; typedef struct s_word_block { char quotation; char *word; int is_conti; int sep; } t_word_block; /* ** utils.c */ void skip_space(char **str); int ft_atoi(const char *fd); int ft_isspace(char c); int ft_isset(char c, const char *set); void *err_malloc(unsigned int n); /* ** prompt_utils.c */ void make_prompt_msg(void); void signal_handler(int signo); void signal_func(void); int ft_exitstatus(int status); int ft_ifsignal(int status); /* ** env_func_1.c && env_func_2.c */ t_env *envp_to_env(char *envp); void add_envlst(t_env *env, char *envp); t_env *make_envlst(char **envp); char *get_value(t_env *env, char *key); t_env *get_env_pointer(t_env *env, char *key); void add_change_env(t_env *env, char *key, char *value); void add_own_path(t_env *env); t_env *set_env_lst(char **envp); /* ** utils2.c */ void kill_process(int pid); void check_d(int *ret, char *buf, char *str); char *triple_join(char *s1, char *s2, char *s3); int strcmp_upper(const char *command, const char *str); /* ** input_sequence.c */ int check_input(char *str); int get_input(char **input); void slash_doing(char **input); void quo_doing(char **input, int quo); void input_sequence(char **input); /* ** make_path_lst.c */ t_path *new_path_one(char *str); t_path *add_path(t_path *path, char *str); t_path *make_path_lst(t_env *env); /* ** work_utils.c */ int is_command(char *cmd); int lstsize_str(t_str *lst); char **str_to_argv(t_commands *node); int lstsize_env(t_env *lst); char **env_to_envp(t_env *env); /* ** work_cmd.c */ int status_return(int status); int path_work(t_commands *node, char *path, t_env *env); int excute_work(t_commands *node, t_env *env); int path_excute(t_commands *node, t_env *env, t_path *path); void work_command(t_commands *node, t_env **env); /* ** minishell.c */ void pipe_doing(t_commands *node, t_env **env); void start_work(t_commands *node, t_env **env); void command_branch(char *command); t_commands *split_separator(char *line, t_env *env); char **env_to_envp(t_env *env); void add_change_env(t_env *env, char *key, char *value); char *get_value(t_env *env, char *key); int list_check(t_commands *lst); void error_check(int err_num, char *error_message); t_env *get_env_pointer(t_env *env, char *key); /* ** free_nodes.c */ void free_path(t_path **path); void free_all_node(t_commands **node); int work_redir(t_commands *node); /* ** command_work.c */ int command_work(t_commands *node, t_env **env, int cmd); /* ** unset_work.c */ int unset_work(t_commands *node, t_env **env); /* ** get_word.c */ t_word_block get_word(char **ref); /* ** commands_addback.c */ void commands_addback(t_commands **lst, t_commands *new); /* ** get_quotiation.c */ void get_quotation(t_word_block *word, char **ref); /* ** get_basic.c */ void get_basic(t_word_block *word, char **ref); /* ** word_init.c */ void word_init(t_word_block *word); void word_join(t_word_block *dest, t_word_block *srcs); void word_free(t_word_block *word); /* ** get_word_utils.c */ void get_str_to_idx(t_word_block *ret, char *line, int i); int is_sep(char c); char *strdup_idx(char *line, int idx); int sep_to_int(char sep, char next); int not_conti(t_word_block *word, char *line, int i); /* ** change_env.c */ void change_env(t_word_block *word, t_env *env); /* ** change_env_utils.c */ int end_env_index(char *word, int i); int end_env_bracelet(char *word, int i); int env_strdup(char **word, int start, int end, char *val); /* ** parse_node.c */ void parse_node(char **ref, t_commands *node, t_env *env); void make_strsadd(t_commands *node, char *str, int redir); #endif <file_sep>/workspace/libs/libftprintf/srcs/case_u.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* case_u.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: joockim <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/08/09 16:50:01 by joockim #+# #+# */ /* Updated: 2020/10/11 19:30:27 by joockim ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/ft_printf.h" int get_u_len(unsigned int n, int div) { int i; i = 0; while (n) { n /= div; i++; } return (i); } char *ft_utoa(unsigned int n, t_item *t) { int len; char *str; if (n == 0 && !t->flag.dot) return (ft_strdup_pr("0")); len = get_u_len(n, 10) > t->flag.prec ? get_u_len(n, 10) : t->flag.prec; str = (char *)malloc(sizeof(char) * (len + 1)); str[len] = 0; while (len--) { str[len] = n % 10 + '0'; n /= 10; } return (str); } void case_u(t_item *t, int *res) { char *str; int str_len; str = ft_utoa(va_arg(t->arg, unsigned int), t); str_len = ft_strlen_pr(str); if (t->flag.minus) *res += putchar_len(str, str_len); if (t->flag.width > str_len) *res += print_zero_space(t, t->flag.width - str_len); if (!t->flag.minus) *res += putchar_len(str, str_len); } <file_sep>/workspace/srcs/work_redir.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* work_redir.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: joockim <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/12 14:21:28 by joockim #+# #+# */ /* Updated: 2021/01/14 19:38:21 by junkang ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/minishell.h" int open_fd_node(t_str *cur, t_commands *node) { int fd; fd = -1; if (cur->redir == REDIR) { node->fdflag = 1; fd = open(cur->next->word, O_WRONLY | O_TRUNC | O_CREAT, 0644 | O_EXCL); } else if (cur->redir == REV_REDIR) { node->fdflag = 2; fd = open(cur->next->word, O_RDONLY); } else if (cur->redir == D_REDIR) { node->fdflag = 1; fd = open(cur->next->word, O_WRONLY | O_APPEND\ | O_CREAT, 0644 | O_EXCL); } return (fd); } int change_to_errcode(int define_num) { if (define_num == PIPE) return (ERR_EMPTY_PIPE); else if (define_num == SEMI) return (ERR_EMPTY_SEMI); else if (define_num == REDIR) return (ERR_EMPTY_REDIR); else if (define_num == D_REDIR) return (ERR_EMPTY_D_REDIR); else if (define_num == REV_REDIR) return (ERR_EMPTY_REV_REDIR); return (ERR_EMPTY_NEWLINE); } t_str *del_str_node(t_str *prev, t_str *cur_node, t_str **head) { if (prev == NULL) *head = cur_node->next->next; else prev->next = cur_node->next->next; free(cur_node->next->word); free(cur_node->next); free(cur_node->word); free(cur_node); return (prev); } int check_redir(t_commands *node, t_str *prev, t_str *head) { if (node->str->next == NULL) { error_check(change_to_errcode(node->sep), ""); return (SYS_SYNTAX); } else if (node->str->next->redir != -1) { error_check(change_to_errcode(node->str->next->redir), ""); return (SYS_SYNTAX); } else { node->fd = open_fd_node(node->str, node); node->str = del_str_node(prev, node->str, &head); } return (0); } int work_redir(t_commands *node) { t_str *head; t_str *prev; head = node->str; prev = NULL; while (node->str) { if (node->str->redir != -1) { if (check_redir(node, prev, head) == SYS_SYNTAX) { node->str = head; return (SYS_SYNTAX); } } prev = node->str; if (node->str != NULL) node->str = node->str->next; else node->str = head; } node->str = head; if (node->str == 0) make_strsadd(node, "", -1); return (0); } <file_sep>/workspace/libs/libftprintf/srcs/case_x.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* case_x.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: joockim <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/08/09 16:50:23 by joockim #+# #+# */ /* Updated: 2020/10/11 19:29:34 by joockim ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/ft_printf.h" char *ft_xtoa(unsigned int n, t_item *t, char *base) { int len; char *str; if (n == 0 && !t->flag.dot) return (ft_strdup_pr("0")); len = get_u_len(n, 16) > t->flag.prec ? get_u_len(n, 16) : t->flag.prec; str = (char *)malloc(sizeof(char) * (len + 1)); str[len] = 0; while (len--) { str[len] = base[n % 16]; n /= 16; } return (str); } void case_x(t_item *t, int *res, char c) { int str_len; char *str; if (c == 'x') str = ft_xtoa(va_arg(t->arg, unsigned int), t, "0123456789abcdef"); else str = ft_xtoa(va_arg(t->arg, unsigned int), t, "0123456789ABCDEF"); str_len = ft_strlen_pr(str); if (t->flag.minus) *res += putchar_len(str, str_len); if (t->flag.width > str_len) *res += print_zero_space(t, t->flag.width - str_len); if (!t->flag.minus) *res += putchar_len(str, str_len); clear_point(str, str_len); } <file_sep>/workspace/srcs/utils2.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* utils2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: joockim <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/15 18:10:04 by joockim #+# #+# */ /* Updated: 2021/01/15 18:10:06 by joockim ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/minishell.h" char *triple_join(char *s1, char *s2, char *s3) { char *tmp; char *res; tmp = ft_strjoin(s1, s2); res = ft_strjoin(tmp, s3); free(tmp); return (res); } void kill_process(int pid) { if (pid == 0) { write(1, "exit\n", 5); exit(0); } else kill(pid, SIGKILL); } void check_d(int *ret, char *buf, char *str) { if (ft_strlen(str)) { *ret = 1; buf[0] = 0; write(1, " \b\b", 4); } else { kill_process(0); } } int strcmp_upper(const char *command, const char *str) { int i; char c; i = -1; while (command[++i]) { if ('A' <= str[i] && str[i] <= 'Z') c = str[i] - 'A' + 'a'; else c = str[i]; if (c != command[i]) return (0); } return (1); } <file_sep>/workspace/srcs/commands_addback.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* commands_addback.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: junkang <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/14 19:38:50 by junkang #+# #+# */ /* Updated: 2021/01/14 19:38:58 by junkang ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/minishell.h" static t_commands *lstlast_next(t_commands *lst) { while (lst) { if (lst->next == 0) return (lst); lst = lst->next; } return (lst); } static t_commands *lstlast_pipe(t_commands *lst) { while (lst) { if (lst->pipe == 0) return (lst); lst = lst->pipe; } return (lst); } void commands_addback(t_commands **lst, t_commands *new) { t_commands *last_semi; t_commands *last_node; if (new == 0 || lst == 0) return ; if (*lst == 0) { *lst = new; return ; } last_semi = lstlast_next(*lst); if (last_semi->sep == PIPE) last_node = lstlast_pipe(last_semi); else last_node = last_semi; if (last_node->sep == PIPE) { last_node->pipe = new; } else if (last_node->sep == SEMI) last_semi->next = new; } <file_sep>/README.md # minishell minishell project ( 42seoul ) ## 🧑‍💻participant joockim ( https://github.com/skamo3 )<br> junkang ( https://github.com/nawaraing ) ## 📚reference subject pdf - https://cdn.intra.42.fr/pdf/pdf/15438/en.subject.pdf<br> <file_sep>/workspace/srcs/split_separator.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* branch.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: joockim <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/12/11 15:06:27 by joockim #+# #+# */ /* Updated: 2020/12/16 17:52:22 by joockim ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/minishell.h" extern int g_error_status; t_commands *make_commands_new(char **ref, t_env *env) { t_commands *node; node = (t_commands *)err_malloc(sizeof(t_commands)); node->sep = -1; node->command = -1; node->str = NULL; node->fd = 0; node->fdflag = 0; node->pipe = NULL; node->next = NULL; parse_node(ref, node, env); return (node); } t_commands *split_separator(char *line, t_env *env) { t_commands *ret; t_commands *node; ret = 0; while (*line) { node = make_commands_new(&line, env); commands_addback(&ret, node); } return (ret); } <file_sep>/workspace/libs/libft/ft_split.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_split.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: joockim <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/04/09 17:27:01 by joockim #+# #+# */ /* Updated: 2020/04/17 23:28:45 by joockim ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" int get_arr(char *s, char c) { int i; int j; i = 0; j = 0; while (*s) { if (*s != c) j++; if (*s == c && j != 0) { j = 0; i++; } s++; } if (*(s - 1) != c) i += 1; return (i); } char **arr_free(char **arr, int a) { while (a-- > 0) free(arr[a]); free(arr); return (0); } int get_arg(char const *s, char c, int i) { int re; re = 0; while (s[i] != c && s[i] != 0) { re++; i++; } return (re); } char **fill(char **arr, int arr_len, char const *s, char c) { int i; int j; int k; i = 0; j = 0; while (s[i] != '\0' && j < arr_len) { k = 0; while (s[i] == c) i++; arr[j] = (char *)malloc(sizeof(char) * get_arg(s, c, i) + 1); if (arr[j] == 0) return (arr_free(arr, j)); while (s[i] != c && s[i] != '\0') arr[j][k++] = s[i++]; arr[j][k] = '\0'; j++; } arr[j] = 0; return (arr); } char **ft_split(char const *s, char c) { int arr_len; char **arr; if (s == 0) return (0); arr_len = get_arr((char *)s, c); if ((arr = (char **)malloc(sizeof(char *) * (arr_len + 1))) == 0) return (0); return (fill(arr, arr_len, s, c)); } <file_sep>/workspace/srcs/prompt_utils.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* prompt_utils.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: joockim <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/15 18:03:35 by joockim #+# #+# */ /* Updated: 2021/01/15 18:03:36 by joockim ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/minishell.h" extern char *g_read_str; extern int g_error_status; void make_prompt_msg(void) { char *path; char *last; path = getcwd(NULL, 0); last = ft_strrchr(path, '/'); ft_printf(COLOR_MAGENTA); ft_printf("dir :"); ft_printf(COLOR_BCYAN); ft_printf("%s", last); ft_printf(COLOR_BRED); ft_printf(" @~"COLOR_BYELLOW"=+"COLOR_BWHITE"=+" COLOR_BGREEN"=+>"); ft_printf(COLOR_RESET); free(path); path = NULL; } void signal_handler(int signo) { write(1, "\b\b \b\b", 6); if (signo == SIGINT) { g_error_status = 1; write(1, "\n", 1); make_prompt_msg(); } } void signal_func(void) { signal(SIGINT, (void *)signal_handler); signal(SIGQUIT, (void *)signal_handler); } int ft_exitstatus(int status) { return ((status >> 8) & 0x000000ff); } int ft_ifsignal(int status) { return ((status & 0177) != 0177 && (status & 0177) != 0); } <file_sep>/workspace/srcs/minishell.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* minishell.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: joockim <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/12/29 22:11:19 by joockim #+# #+# */ /* Updated: 2021/01/15 19:13:08 by joockim ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/minishell.h" char *g_read_str; int g_error_status; static void in_child_process(t_commands *node, int p1[2], t_env **env) { if (node->pipe) { close(p1[0]); dup2(p1[1], STDOUT_FILENO); } if (node->fd != STDIN_FILENO && dup2(node->fd, STDIN_FILENO) < 0) exit(0); work_command(node, env); exit(0); } void pipe_doing(t_commands *node, t_env **env) { int p1[2]; pid_t pid; int status; while (node) { if (node->pipe) { pipe(p1); node->pipe->fd = p1[0]; } if (!(pid = fork())) in_child_process(node, p1, env); else { if (node->pipe) close(p1[1]); if (node->fd != STDIN_FILENO) close(node->fd); waitpid(pid, &status, 0); } node = node->pipe; } } void start_work(t_commands *node, t_env **env) { while (node) { if (node->pipe) { pipe_doing(node, env); } else { work_command(node, env); } node = node->next; } } int main(int argc, char **argv, char **envp) { char *input; t_env *env; t_commands *node; int err_num; argc = 0; env = set_env_lst(envp); signal_func(); while (1) { input_sequence(&input); node = split_separator(input, env); if ((err_num = list_check(node)) < 0) { error_check(err_num, ""); g_error_status = SYS_SYNTAX; } else start_work(node, &env); free_all_node(&node); free(input); input = NULL; } return (0); argv = 0; } <file_sep>/workspace/srcs/error_check.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* error_check.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: joockim <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/12 14:21:22 by joockim #+# #+# */ /* Updated: 2021/01/14 19:39:56 by junkang ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/minishell.h" void error_check(int err_num, char *error_message) { ft_printf(COLOR_BRED"minishell: "COLOR_BGREEN); if (err_num == ERR_EMPTY_SEMI) ft_printf("%s\n", ERR_EMPTY_SEMI_S); else if (err_num == ERR_EMPTY_PIPE) ft_printf("%s\n", ERR_EMPTY_PIPE_S); else if (err_num == ERR_EMPTY_REDIR) ft_printf("%s\n", ERR_EMPTY_REDIR_S); else if (err_num == ERR_EMPTY_REV_REDIR) ft_printf("%s\n", ERR_EMPTY_REV_REDIR_S); else if (err_num == ERR_EMPTY_D_REDIR) ft_printf("%s\n", ERR_EMPTY_D_REDIR_S); else if (err_num == ERR_EMPTY_NEWLINE) ft_printf("%s\n", ERR_EMPTY_NEWLINE_S); else if (err_num == ERR_EXPORT) ft_printf("export: `=%s': not a valid identifier\n", \ error_message); else if (err_num == SYS_CMD_NOT_FOUND) ft_printf("%s: command not found\n", error_message); else if (err_num == ERR_NO_SUCH_FILE) ft_printf("cd: %s: No such file or directory\n", error_message); ft_printf(COLOR_RESET); } <file_sep>/workspace/libs/libftprintf/srcs/case_csper.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* case_cs.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: joockim <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/08/09 16:49:01 by joockim #+# #+# */ /* Updated: 2020/10/11 19:20:53 by joockim ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/ft_printf.h" void case_c(t_item *t, int *res) { char c; c = va_arg(t->arg, int); if (t->flag.minus) *res += putchar_len(&c, 1); while (--t->flag.width > 0) *res += write(1, " ", 1); if (!t->flag.minus) *res += putchar_len(&c, 1); } int write_space_s(t_item *t, int len) { int res; res = len; while (len--) { if (t->flag.zero && !t->flag.minus) write(1, "0", 1); else write(1, " ", 1); } return (res); } void case_s(t_item *t, int *res) { char *s; int str_len; s = va_arg(t->arg, char*); if (s == 0) s = "(null)"; str_len = ft_strlen_pr(s); if (t->flag.dot && t->flag.prec < str_len) str_len = t->flag.prec; if (t->flag.dot && t->flag.prec == -1) str_len = 0; if (t->flag.minus || t->flag.width <= str_len) *res += write(1, s, str_len); if (t->flag.width > str_len) *res += write_space_s(t, t->flag.width - str_len); if (!t->flag.minus && t->flag.width > str_len) *res += write(1, s, str_len); } void case_per(t_item *t, int *res) { if (t->flag.minus) *res += write(1, "%", 1); if (t->flag.width > 1) *res += write_space_s(t, t->flag.width - 1); if (!t->flag.minus) *res += write(1, "%", 1); } <file_sep>/workspace/libs/libftprintf/srcs/ft_printf.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_printf.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: joockim <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/07/14 17:09:52 by joockim #+# #+# */ /* Updated: 2020/08/19 20:28:27 by joockim ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/ft_printf.h" int handle(const char *str, t_item *t, int *res) { t->i += 1; make_flag(str, t); if (str[t->i] == 'd' || str[t->i] == 'i') case_d(t, res); else if (str[t->i] == 'c') case_c(t, res); else if (str[t->i] == 's') case_s(t, res); else if (str[t->i] == 'p') case_p(t, res); else if (str[t->i] == 'u') case_u(t, res); else if (str[t->i] == 'x' || str[t->i] == 'X') case_x(t, res, str[t->i]); else if (str[t->i] == '%') case_per(t, res); else return (-1); return (1); } int ft_printf(const char *str, ...) { int res; t_item t; res = 0; t.i = 0; va_start(t.arg, str); while (str[t.i]) { if (str[t.i] == '%') { if (handle(str, &t, &res) == -1) return (-1); } else { write(1, &str[t.i], 1); res++; } t.i++; } va_end(t.arg); return (res); } <file_sep>/workspace/libs/libftprintf/srcs/case_d.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* case_d.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: joockim <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/07/30 16:16:23 by joockim #+# #+# */ /* Updated: 2020/10/11 19:30:10 by joockim ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/ft_printf.h" int get_n_len(long int n) { int i; i = 0; if (n < 0) n *= -1; while (n > 0) { n /= 10; i++; } return (i); } char *ft_itoa_pr(long int n, t_item *t) { int len; char *str; if (n == 0 && !t->flag.dot) return (ft_strdup_pr("0")); len = get_n_len(n) > t->flag.prec ? get_n_len(n) : t->flag.prec; str = (char *)malloc(sizeof(char) * (len + 1)); str[len] = 0; while (len--) { if (n < 0) n *= -1; str[len] = n % 10 + '0'; n /= 10; } return (str); } int print_zero_space(t_item *t, int len) { int res; res = len; while (len--) { if (t->flag.zero && t->flag.prec <= -1 && t->flag.dot == 0) write(1, "0", 1); else write(1, " ", 1); } return (res); } void case_d(t_item *t, int *res) { long int n; int str_len; char *str; n = va_arg(t->arg, int); str = ft_itoa_pr(n, t); str_len = ft_strlen_pr(str); if (n < 0) { t->flag.width--; if (t->flag.minus || (t->flag.zero && !t->flag.dot) || t->flag.width <= str_len) *res += write(1, "-", 1); } if (t->flag.minus) *res += putchar_len(str, str_len); if (t->flag.width > str_len) *res += print_zero_space(t, t->flag.width - str_len); if (n < 0 && !t->flag.minus && (!t->flag.zero || t->flag.dot) && t->flag.width > str_len) *res += write(1, "-", 1); if (!t->flag.minus) *res += putchar_len(str, str_len); clear_point(str, str_len); } <file_sep>/workspace/srcs/change_env_utils.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* change_env_utils.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: junkang <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/14 19:38:32 by junkang #+# #+# */ /* Updated: 2021/01/14 19:38:44 by junkang ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/minishell.h" int end_env_index(char *word, int i) { while (word[++i]) { if (word[i] == '.' || word[i] == '$' ||\ word[i] == '?' || word[i] == ':' ||\ word[i] == ' ' || word[i] == '\'' || word[i] == '=') break ; } return (i); } int end_env_bracelet(char *word, int i) { while (word[++i]) { if (word[i] == '}') break ; } return (i); } int env_strdup(char **word, int start, int end, char *val) { int ret; char c; char *new; char *tmp; c = (*word)[start]; (*word)[start] = 0; new = ft_strdup((*word)); (*word)[start] = c; tmp = new; new = ft_strjoin(new, val); free(tmp); ret = ft_strlen(new) - 1; tmp = new; new = ft_strjoin(new, &((*word)[end])); free(tmp); free(*word); (*word) = new; return (ret); } <file_sep>/workspace/srcs/env_func_1.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* env_func_1.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: joockim <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/15 17:32:41 by joockim #+# #+# */ /* Updated: 2021/01/15 17:53:27 by joockim ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/minishell.h" extern int g_error_status; t_env *get_env_pointer(t_env *env, char *key) { while (env) { if (!ft_strncmp(key, env->key, ft_strlen(key)) && !ft_strncmp(key, env->key, ft_strlen(env->key))) return (env); env = env->next; } return (NULL); } void add_change_env(t_env *env, char *key, char *value) { t_env *cur_env; if ((cur_env = get_env_pointer(env, key))) { free(cur_env->value); cur_env->value = ft_strdup(value); } else { while (env->next) env = env->next; cur_env = (t_env *)err_malloc(sizeof(t_env)); cur_env->key = ft_strdup(key); cur_env->value = ft_strdup(value); cur_env->next = NULL; env->next = cur_env; } } void add_own_path(t_env *env) { char *temp; char *excute_path; t_env *path_env; path_env = get_env_pointer(env, "PATH"); excute_path = getcwd(0, 0); temp = triple_join(excute_path, ":", path_env->value); free(excute_path); excute_path = NULL; free(path_env->value); path_env->value = temp; } t_env *set_env_lst(char **envp) { int shlvl_tmp; char *tmp; t_env *env; env = make_envlst(envp); g_error_status = 0; shlvl_tmp = ft_atoi(get_value(env, "SHLVL")); tmp = ft_itoa(++shlvl_tmp); add_change_env(env, "SHLVL", tmp); free(tmp); if (ft_strncmp(get_value(env, "SHELL"), "/minishell", ft_strlen("/minishell"))) add_own_path(env); add_change_env(env, "SHELL", "/minishell"); return (env); } <file_sep>/workspace/srcs/unset_work.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* unset_work.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: joockim <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/15 18:37:27 by joockim #+# #+# */ /* Updated: 2021/01/15 18:37:28 by joockim ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/minishell.h" static t_env *env_prev_cur(t_env *env, char *key, t_env **prev) { *prev = NULL; while (env) { if (!ft_strncmp(key, env->key, ft_strlen(key)) && !ft_strncmp(key, env->key, ft_strlen(env->key))) return (env); *prev = env; env = env->next; } return (NULL); } static void free_env_node(t_env *node) { free(node->key); free(node->value); free(node); } int unset_work(t_commands *node, t_env **env) { t_str *cur; char *param; t_env *cur_env; t_env *prev_env; cur = node->str->next; while (cur) { param = cur->word; cur_env = env_prev_cur(*env, param, &prev_env); if (cur_env) { if (prev_env == NULL) *env = (*env)->next; else prev_env->next = cur_env->next; free_env_node(cur_env); } cur = cur->next; } return (1); } <file_sep>/workspace/srcs/get_basic.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_basic.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: junkang <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/14 19:37:56 by junkang #+# #+# */ /* Updated: 2021/01/14 19:37:58 by junkang ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/minishell.h" static int get_index_basic(t_word_block *ret, char **ref) { char *line; int i; line = *ref; i = -1; while (line[++i]) { if (ft_isset(line[i], "\'\"") || ft_isspace(line[i])) break ; else if (is_sep(line[i])) { ret->sep = sep_to_int(line[i], line[i + 1]); break ; } else if (ft_isset(line[i], "\\")) { line[i] = -1; i++; } } return (i); } void get_basic(t_word_block *word, char **ref) { char *line; int i; line = *ref; i = get_index_basic(word, ref); free(word->word); word->word = strdup_idx(line, i); if (ft_isspace(line[i]) == 0 && line[i] != 0 && is_sep(line[i]) == 0) word->is_conti = 1; else { word->is_conti = 0; i = not_conti(word, line, i); } (*ref) += i; skip_space(ref); } <file_sep>/workspace/libs/libftprintf/srcs/case_p.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* case_p.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: joockim <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/08/09 16:49:48 by joockim #+# #+# */ /* Updated: 2020/10/11 19:29:16 by joockim ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/ft_printf.h" char *ft_ptoa(unsigned long long p, t_item *t, char *base) { unsigned long long n; int len; char *res; int a; len = 0; n = p; if (p == 0 && !t->flag.dot) return (ft_strdup_pr("0")); while (n) { n /= 16; len++; } res = (char *)malloc(sizeof(char) * (len + 1)); res[len] = 0; while (len--) { a = p % 16; res[len] = base[a]; p /= 16; } return (res); } int write_space_p(int len) { int res; res = len; while (len--) write(1, " ", 1); return (res); } void case_p(t_item *t, int *res) { unsigned long long n; char *str; int str_len; n = va_arg(t->arg, unsigned long long); str = ft_ptoa(n, t, "0123456789abcdef"); str_len = ft_strlen_pr(str) + 2; if (t->flag.minus || t->flag.width <= str_len) { *res += write(1, "0x", 2); *res += write(1, str, str_len - 2); } if (t->flag.width > str_len) *res += write_space_p(t->flag.width - str_len); if (!t->flag.minus && t->flag.width > str_len) { *res += write(1, "0x", 2); *res += write(1, str, str_len - 2); } clear_point(str, str_len - 2); } <file_sep>/workspace/libs/libftprintf/Makefile NAME = libftprintf.a CC = gcc FLAGS = -Werror -Wextra -Wall INCLUDE = ./include/ft_printf.h SRCS = $(addprefix ./srcs/, ft_printf.c make_flags.c utils.c case_csper.c case_p.c case_x.c case_d.c case_u.c) OBJS = $(SRCS:.c=.o) .PHONY : all clean fclean re all : $(NAME) $(NAME) : $(OBJS) @ar rc $@ $^ @echo ---------make success libftprintf.a---------- .c.o : @$(CC) $(FLAGS) -c $< -o $(<:.c=.o) -include $(INCLUDE) clean : @rm -f $(OBJS) fclean : clean @rm -f $(NAME) re : fclean all <file_sep>/workspace/libs/libftprintf/include/ft_printf.h /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_printf.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: joockim <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/07/21 18:15:29 by joockim #+# #+# */ /* Updated: 2020/10/14 09:22:42 by joockim ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef FT_PRINTF_H # define FT_PRINTF_H # include <stdarg.h> # include <stdlib.h> # include <unistd.h> # include <stdio.h> typedef struct s_flag { int dot; int minus; int star; int width; int zero; int prec; } t_flag; typedef struct s_item { int i; va_list arg; t_flag flag; } t_item; int ft_printf(const char *str, ...); int handle(const char *str, t_item *t, int *res); void init_flag(t_flag *t); int get_int(const char *str, t_item *t); void star(t_item *t); void make_flag(const char *str, t_item *t); int ft_isdigit_pr(int c); int ft_strlen_pr(char *str); int putchar_len(char *str, int len); char *ft_strdup_pr(const char *string); void clear_point(char *p, int len); int get_n_len(long int n); char *ft_itoa_pr(long int n, t_item *t); int print_zero_space(t_item *t, int len); void case_d(t_item *t, int *res); void case_c(t_item *t, int *res); int write_space_s(t_item *t, int len); void case_s(t_item *t, int *res); void case_per(t_item *t, int *res); char *ft_ptoa(unsigned long long p, t_item *t, char *base); int write_space_p(int len); void case_p(t_item *t, int *res); int get_u_len(unsigned int n, int div); char *ft_utoa(unsigned int n, t_item *t); void case_u(t_item *t, int *res); char *ft_xtoa(unsigned int n, t_item *t, char *base); void case_x(t_item *t, int *res, char c); #endif <file_sep>/workspace/libs/libftprintf/srcs/make_flags.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* make_flags.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: joockim <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/07/21 18:13:06 by joockim #+# #+# */ /* Updated: 2020/10/14 09:25:20 by joockim ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/ft_printf.h" int ft_isdigit_pr(int c) { return (c >= '0' && c <= '9'); } void init_flag(t_flag *t) { t->dot = 0; t->minus = 0; t->width = -1; t->zero = 0; t->prec = -1; } int get_int(const char *str, t_item *t) { int r; r = 0; while (ft_isdigit_pr(str[t->i])) { r = r * 10 + (str[t->i] - '0'); t->i++; } return (r); } void star(t_item *t) { int n; n = va_arg(t->arg, int); if (t->flag.dot == 0) { if (n < 0) { t->flag.minus = 1; t->flag.zero = 0; n *= -1; } t->flag.width = n; } if (t->flag.dot == 1) { if (n < 0) t->flag.dot = 0; t->flag.prec = n; } t->i++; } void make_flag(const char *str, t_item *t) { init_flag(&t->flag); while (str[t->i] == '-' || str[t->i] == '0') { if (str[t->i] == '-') { t->flag.minus = 1; t->flag.zero = 0; } else t->flag.zero = 1; t->i++; } if (ft_isdigit_pr(str[t->i]) && !t->flag.dot) t->flag.width = get_int(str, t); if (str[t->i] == '*') star(t); if (str[t->i] == '.') { t->flag.dot = 1; t->i++; if (ft_isdigit_pr(str[t->i])) t->flag.prec = get_int(str, t); if (str[t->i] == '*' && t->flag.prec == -1) star(t); } } <file_sep>/workspace/srcs/work_utils.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* work_utils.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: joockim <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/15 18:36:00 by joockim #+# #+# */ /* Updated: 2021/01/15 18:48:02 by joockim ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/minishell.h" int is_command(char *cmd) { if (ft_strlen(cmd) == 2 && ft_strncmp("cd", cmd, 2) == 0) return (CD); else if (ft_strlen(cmd) == 6 && ft_strncmp("export", cmd, 6) == 0) return (EXPORT); else if (ft_strlen(cmd) == 5 && ft_strncmp("unset", cmd, 5) == 0) return (UNSET); else if (ft_strlen(cmd) == 4 && ft_strncmp("exit", cmd, 4) == 0) return (EXIT); return (-1); } int lstsize_str(t_str *lst) { int i; t_str *move; i = 0; move = lst; while (move != 0) { move = move->next; i++; } return (i); } char **str_to_argv(t_commands *node) { t_str *lst; char **ret; int size; int i; lst = node->str->next; size = lstsize_str(lst); ret = (char **)err_malloc(sizeof(char *) * (size + 2)); i = 0; ret[i] = ft_strdup(ft_strrchr(node->str->word, '/') + 1); while (++i != size + 1) { ret[i] = lst->word; lst = lst->next; } ret[size + 1] = NULL; return (ret); } int lstsize_env(t_env *lst) { int i; t_env *move; i = 0; move = lst; while (move != 0) { move = move->next; i++; } return (i); } char **env_to_envp(t_env *env) { char **work; char **ret; int size; char *str; work = (char **)err_malloc(sizeof(char *) * ((size = lstsize_env(env)) + 1)); ret = work; while (env) { str = triple_join(env->key, "=", env->value); *work = str; work++; env = env->next; } *work = NULL; return (ret); } <file_sep>/workspace/srcs/free_nodes.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* free_nodes.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: joockim <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/15 17:03:10 by joockim #+# #+# */ /* Updated: 2021/01/15 17:03:12 by joockim ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/minishell.h" extern char *g_read_str; extern int g_error_status; static void clear_str_node(t_str **str) { t_str *tmp; while (*str) { tmp = *str; *str = (*str)->next; free(tmp->word); tmp->word = NULL; free(tmp); tmp = NULL; } } static void pipe_clear(t_commands **node) { t_commands **pipe_node; t_commands *tmp; pipe_node = node; while (*pipe_node) { tmp = *pipe_node; clear_str_node(&(*pipe_node)->str); *pipe_node = (*pipe_node)->pipe; free(tmp); tmp = NULL; } } static void clear_node(t_commands **node) { t_commands *tmp; tmp = *node; clear_str_node(&(*node)->str); *node = (*node)->next; free(tmp); tmp = NULL; } void free_all_node(t_commands **node) { while (*node) { if ((*node)->pipe) pipe_clear(&(*node)->pipe); clear_node(node); } } <file_sep>/workspace/libs/libft/ft_strtrim.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strtrim.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: joockim <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/04/09 17:29:30 by joockim #+# #+# */ /* Updated: 2020/04/09 17:32:11 by joockim ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" int isset(char c, char const *set) { int res; res = 1; while (*set) { if (*set == c) res = 0; set++; } return (res); } int get_front(char const *s1, char const *set) { int i; int res; i = 0; res = 0; while (s1[i]) { if (isset(s1[i], set)) { res = i; break ; } i++; } return (res); } int get_back(char const *s1, char const *set, int len) { int res; res = 0; while (len) { if (isset(s1[len], set)) { res = len; break ; } len--; } return (res); } char *ft_strtrim(char const *s1, char const *set) { int i; int front; int copy_len; char *res; front = get_front(s1, set); copy_len = get_back(s1, set, ft_strlen(s1) - 1) - front + 1; if (copy_len == 1) { res = malloc(sizeof(char)); *res = 0; return (res); } if ((res = (char *)malloc(sizeof(char) * copy_len + 1)) == 0) return (0); i = 0; while (copy_len--) res[i++] = s1[front++]; res[i] = '\0'; return (res); } <file_sep>/workspace/srcs/command_work.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* command_work.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: joockim <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/12 14:21:47 by joockim #+# #+# */ /* Updated: 2021/01/15 19:10:29 by joockim ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/minishell.h" static int cd_work(t_commands *node, t_env *env) { char *buf; if ((buf = getcwd(0, 0)) == NULL) return (-1); add_change_env(env, "OLDPWD", buf); free(buf); if (node->str->next == 0) { if (chdir(get_value(env, "HOME")) == -1) return (-1); } else if (chdir(node->str->next->word) == -1) { error_check(ERR_NO_SUCH_FILE, node->str->next->word); return (-1); } if ((buf = getcwd(0, 0)) == NULL) return (-1); add_change_env(env, "PWD", buf); free(buf); buf = NULL; return (1); } static int export_work(t_commands *node, t_env *env) { t_str *cur; char *param; char *tmp; cur = node->str->next; while (cur) { param = cur->word; if ((tmp = ft_strchr(param, '='))) { if (tmp == param) { error_check(ERR_EXPORT, param + 1); return (-1); } *tmp = 0; add_change_env(env, param, tmp + 1); *tmp = '='; } cur = cur->next; } return (1); } static void exit_work(t_commands *node) { int num; num = 0; if (node->str->next) num = ft_atoi(node->str->next->word); exit(num); } int command_work(t_commands *node, t_env **env, int cmd) { if (cmd == CD) return (cd_work(node, *env)); else if (cmd == EXPORT) return (export_work(node, *env)); else if (cmd == UNSET) { unset_work(node, env); return (1); } else if (cmd == EXIT) exit_work(node); return (-1); } <file_sep>/workspace/srcs/parse_node.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* parse_node.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: junkang <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/14 19:34:52 by junkang #+# #+# */ /* Updated: 2021/01/14 19:38:12 by junkang ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/minishell.h" void make_strsadd(t_commands *node, char *str, int redir) { t_str *head; t_str *new; new = (t_str *)err_malloc(sizeof(t_str)); new->redir = redir; new->word = ft_strdup(str); new->next = NULL; if (node->str == NULL) node->str = new; else { head = node->str; while (node->str->next) node->str = node->str->next; node->str->next = new; node->str = head; } } static int save_node(t_commands *node, t_word_block *word) { if (word->sep == SPACE) make_strsadd(node, word->word, -1); else if (word->sep == REDIR || word->sep == D_REDIR || \ word->sep == REV_REDIR) { if (ft_strlen(word->word) != 0) make_strsadd(node, word->word, -1); make_strsadd(node, "", word->sep); } else if (word->sep == PIPE || word->sep == SEMI) { if (ft_strlen(word->word) != 0) make_strsadd(node, word->word, -1); node->sep = word->sep; word_free(word); return (1); } else if (word->sep == 0) { make_strsadd(node, word->word, -1); word_free(word); return (1); } word_free(word); return (0); } void parse_node(char **ref, t_commands *node, t_env *env) { t_word_block word; t_word_block part; word_init(&word); skip_space(ref); while ((part = get_word(ref)).word) { if (part.quotation != '\'') change_env(&part, env); word_join(&word, &part); if (word.is_conti == 0) { if (1 == save_node(node, &word)) break ; } } if (node->str == NULL) make_strsadd(node, "", -1); } <file_sep>/workspace/srcs/get_word_utils.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_word_utils.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: junkang <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/14 19:38:05 by junkang #+# #+# */ /* Updated: 2021/01/14 19:38:06 by junkang ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/minishell.h" void get_str_to_idx(t_word_block *ret, char *line, int i) { char tmp; tmp = line[i]; line[i] = 0; free(ret->word); ret->word = ft_strdup(line); line[i] = tmp; } int is_sep(char c) { if (ft_isset(c, "|;><")) return (1); return (0); } char *strdup_idx(char *line, int idx) { char *ret; char tmp; tmp = line[idx]; line[idx] = 0; ret = ft_strdup(line); line[idx] = tmp; return (ret); } int sep_to_int(char sep, char next) { if (sep == '>' && next == '>') return (D_REDIR); else if (sep == '>') return (REDIR); else if (sep == '<') return (REV_REDIR); else if (sep == '|') return (PIPE); else if (sep == ';') return (SEMI); return (-1); } int not_conti(t_word_block *word, char *line, int i) { while (ft_isspace(line[i])) i++; if (line[i] == 0) word->sep = 0; else if (is_sep(line[i])) { word->sep = sep_to_int(line[i], line[i + 1]); i++; if (word->sep == D_REDIR) i++; } else word->sep = SPACE; return (i); } <file_sep>/workspace/Makefile # **************************************************************************** # # # # ::: :::::::: # # Makefile :+: :+: :+: # # +:+ +:+ +:+ # # By: joockim <<EMAIL>> +#+ +:+ +#+ # # +#+#+#+#+#+ +#+ # # Created: 2020/12/10 16:22:30 by joockim #+# #+# # # Updated: 2021/01/09 01:31:17 by joockim ### ########.fr # # # # **************************************************************************** # NAME = minishell CC = gcc UTILS = ./libs/ EXCUTE_PATH = ./srcs/ CFLAGS = -Werror -Wextra -Wall -g LIBFT_FLAGS = -L ${UTILS}libft -lft -L ${UTILS}libftprintf -lftprintf FLAGS = $(LIBFT_FLAGS) SRCS = $(addprefix ./srcs/, \ command_work.c \ unset_work.c \ split_separator.c \ list_check.c \ error_check.c \ utils.c \ work_redir.c \ commands_addback.c \ get_word.c \ get_word_utils.c \ word_init.c \ get_basic.c \ get_quotation.c \ change_env.c \ change_env_utils.c \ parse_node.c \ make_path_lst.c \ free_nodes.c \ input_sequence.c \ env_func_1.c \ env_func_2.c \ prompt_utils.c \ utils2.c \ work_utils.c \ work_cmd.c \ minishell.c) OBJS = $(SRCS:.c=.o) EXCUTABLE = pwd echo env .phony : all clean fclean re all : ${NAME} ${NAME} : ${OBJS} @make bonus -C ${UTILS}libft @make -C ${UTILS}libftprintf @${CC} ${FLAGS} ${OBJS} -o ${NAME} @${CC} ${FLAGS} -o pwd ${EXCUTE_PATH}excute_pwd.c @${CC} ${FLAGS} -o echo ${EXCUTE_PATH}excute_echo.c @${CC} ${FLAGS} -o env ${EXCUTE_PATH}excute_env.c @echo ----------make success minishell---------- clean : @make clean -C ${UTILS}libft @make clean -C ${UTILS}libftprintf @rm -f ${OBJS} @rm -f ${EXCUTABLE} @echo ------------do clean------------ fclean : clean @make fclean -C ${UTILS}libft @make fclean -C ${UTILS}libftprintf @rm -f ${NAME} @echo ------------do fclean------------ re : fclean all <file_sep>/workspace/srcs/make_path_lst.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* make_path_lst.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: joockim <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/15 16:42:17 by joockim #+# #+# */ /* Updated: 2021/01/15 16:59:55 by joockim ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/minishell.h" void free_path(t_path **path) { t_path *tmp; while (*path) { tmp = *path; *path = (*path)->next; free(tmp->path); tmp->path = NULL; free(tmp); tmp = NULL; } } t_path *new_path_one(char *str) { t_path *res; res = (t_path *)err_malloc(sizeof(t_path)); res->path = str; res->next = NULL; return (res); } t_path *add_path(t_path *path, char *str) { t_path *head; head = path; if (path == NULL) { path = new_path_one(str); return (path); } else { while (path->next) path = path->next; path->next = new_path_one(str); } return (head); } t_path *make_path_lst(t_env *env) { t_path *res; char *path; char *point; res = NULL; if ((path = get_value(env, "PATH")) == NULL) return (add_path(res, ft_strdup(""))); point = ft_strchr(path, ':'); while (path) { if (point) { res = add_path(res, ft_substr(path, 0, point - path)); path = point + 1; point = ft_strchr(path, ':'); } else { res = add_path(res, ft_strdup(path)); path = NULL; } } return (res); } <file_sep>/workspace/srcs/get_quotation.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_quotation.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: junkang <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/14 19:39:25 by junkang #+# #+# */ /* Updated: 2021/01/14 19:39:40 by junkang ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/minishell.h" static void get_single_quotation(t_word_block *word, char **ref) { char *line; int i; (*ref)++; line = *ref; i = -1; while (line[++i]) if (line[i] == word->quotation) break ; free(word->word); word->word = strdup_idx(line, i); i++; if (ft_isspace(line[i]) == 0 && line[i] != 0 && is_sep(line[i]) == 0) word->is_conti = 1; else { word->is_conti = 0; i = not_conti(word, line, i); } (*ref) += i; skip_space(ref); } static int get_index_double(t_word_block *word, char **ref) { char *line; int i; line = *ref; i = -1; while (line[++i]) { if (line[i] == word->quotation) break ; else if (line[i] == '\\' && (line[i + 1] == '\\' ||\ line[i + 1] == '\"' || line[i + 1] == '$')) { line[i] = -1; i++; } } return (i); } /* ** 큰따옴표로 묶인 단어 파싱 ** 생략해야하는 \의 경우, 그 자리에 -1로 바꿔서 저장 ** param : 필요한 정보를 저장할 구조체, 원본 글 */ static void get_double_quotation(t_word_block *word, char **ref) { char *line; int i; (*ref)++; line = *ref; i = get_index_double(word, ref); free(word->word); word->word = strdup_idx(line, i); i++; if (ft_isspace(line[i]) == 0 && line[i] != 0 && is_sep(line[i]) == 0) word->is_conti = 1; else { word->is_conti = 0; i = not_conti(word, line, i); } (*ref) += i; skip_space(ref); } void get_quotation(t_word_block *word, char **ref) { if ((*ref)[0] == '\'') get_single_quotation(word, ref); else get_double_quotation(word, ref); } <file_sep>/workspace/srcs/input_sequence.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* input_sequence.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: joockim <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/15 17:16:19 by joockim #+# #+# */ /* Updated: 2021/01/15 17:16:21 by joockim ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/minishell.h" extern char *g_read_str; extern int g_error_status; int check_input(char *str) { int flag; flag = 0; while (*str) { if (*str == '\\' && *(str + 1) != 0 && flag != SQU) str++; else if (*str == '"' && flag == 0) flag = BQU; else if (*str == '\'' && flag == 0) flag = SQU; else if (*str == '"' && flag == 1) flag = 0; else if (*str == '\'' && flag == 2) flag = 0; else if (*str == '\\' && flag == 0 && *(str + 1) == 0) flag = BSL; str++; } return (flag); } int get_input(char **input) { int ret; char buf[2]; char *temp; ret = 1; buf[0] = 0; buf[1] = 0; g_read_str = ft_strjoin("", ""); while (ret && buf[0] != '\n') { ret = read(0, buf, 1); if (ret == 0) check_d(&ret, buf, g_read_str); if (buf[0] != '\n' && ret != 0) { temp = ft_strjoin(g_read_str, buf); free(g_read_str); g_read_str = temp; } } *input = g_read_str; return (check_input(g_read_str)); } void slash_doing(char **input) { int flag; char *tmp; char *more; write(1, ">", 1); tmp = ft_substr(*input, 0, ft_strlen(*input) - 1); free(*input); flag = get_input(&more); *input = ft_strjoin(tmp, more); free(more); free(tmp); if (flag == BSL) slash_doing(input); } void quo_doing(char **input, int quo) { int flag; char *temp; char *more; if (quo == SQU) write(1, "quote>", 6); else write(1, "D_quote>", 8); temp = ft_strjoin(*input, "\n"); free(*input); flag = get_input(&more); *input = ft_strjoin(temp, more); free(more); free(temp); if (flag != quo) quo_doing(input, quo); } void input_sequence(char **input) { int flag; if (g_error_status != 130) make_prompt_msg(); flag = get_input(input); if (flag == BSL) slash_doing(input); else if (flag == SQU) quo_doing(input, SQU); else if (flag == BQU) quo_doing(input, BQU); }
ad25f1bba221bc060151754e121dc7ba2faefe3c
[ "Markdown", "C", "Makefile" ]
39
Makefile
junckim/minishell
93b12fd85b593816f2bbac7891c84da5500c7eef
fee21295cf4eddca30750671abd0074c6132197c
refs/heads/master
<file_sep>package buu.informatics.s59160578.garage import android.app.Activity import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button import android.widget.EditText import android.widget.TextView import androidx.databinding.adapters.TextViewBindingAdapter.setText class MainActivity: AppCompatActivity() { private val carInfo= Array(3){CarInfo()} private var ind = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) findViewById<Button>(R.id.C1).setOnClickListener { ind = 0 updateEditText(it) } findViewById<Button>(R.id.C2).setOnClickListener { ind = 1 updateEditText(it) } findViewById<Button>(R.id.C3).setOnClickListener { ind = 2 updateEditText(it) } findViewById<Button>(R.id.button_cancel).setOnClickListener { delDataCar(it) } findViewById<Button>(R.id.button_confirm).setOnClickListener { updateDataCar(it) } } private fun updateDataCar(view: View){ carInfo[ind]?.idCar = findViewById<EditText>(R.id.editText_id).text.toString() carInfo[ind]?.brand = findViewById<EditText>(R.id.editText_brand).text.toString() carInfo[ind]?.name = findViewById<EditText>(R.id.editText_name).text.toString() when(ind){ 0 -> findViewById<Button>(R.id.C1).text = findViewById<EditText>(R.id.editText_id).text.toString() 1 -> findViewById<Button>(R.id.C2).text = findViewById<EditText>(R.id.editText_id).text.toString() 2 -> findViewById<Button>(R.id.C3).text = findViewById<EditText>(R.id.editText_id).text.toString() } invalidateOptionsMenu() } private fun delDataCar(view: View){ carInfo[ind]?.idCar = "" carInfo[ind]?.brand = "" carInfo[ind]?.name = "" when(ind){ 0 -> findViewById<Button>(R.id.C1).text = "ว่าง" 1 -> findViewById<Button>(R.id.C2).text = "ว่าง" 2 -> findViewById<Button>(R.id.C3).text = "ว่าง" } invalidateOptionsMenu() } private fun updateEditText(view: View){ findViewById<EditText>(R.id.editText_id).setText(carInfo[ind].idCar) findViewById<EditText>(R.id.editText_brand).setText(carInfo[ind].brand) findViewById<EditText>(R.id.editText_name).setText(carInfo[ind].name) } } <file_sep>package buu.informatics.s59160578.garage data class CarInfo( var idCar: String = "", var brand: String = "", var name: String = "" )
1bc7a05a59e4d8dcacb0f5fd5dad957741a9084a
[ "Kotlin" ]
2
Kotlin
RHiaHoa/PJ4_T-Kob_Garage
61c5a0517131743b31a3ae5183a47c3c0ae2607e
f7e7650cde71fc6e77b2005b391974c6b1d61a2f
refs/heads/master
<file_sep># simple_node Simple express server with passport <file_sep>var express = require('express'); var morgan = require('morgan'); var path = require('path'); var stylus = require('express-stylus'); var koutoSwiss = require('kouto-swiss'); var jeet = require('jeet'); var app = express(); var publicDir = path.resolve(__dirname + '/public'); app.use(morgan("default")); app.use(stylus({ src: publicDir, use: [koutoSwiss(), jeet()], import: ['kouto-swiss', 'jeet'] })); app.engine('ejs', require('ejs').renderFile); app.set('view engine', 'ejs'); app.use(express.static(__dirname + '/public')); app.get('/', function(req, res, next){ res.render('index'); }); app.listen(3000, function(){ console.log('listen to port 3000'); });
c24e6fe5b42610d9493d9409b575e01c29ab2a9a
[ "Markdown", "JavaScript" ]
2
Markdown
codingleo/simple_node
29edd1e28b82cc9a98037781dfed8bf19303d138
44cc4a7d80bce0e844e7c741b203e2c48f78ddd1
refs/heads/master
<repo_name>Sandy4321/recipes-classifier<file_sep>/FlaskApi/app.py # -*- coding: utf-8 -*- from nltk.stem import WordNetLemmatizer import flask from flask import Flask, jsonify, request from flask_cors import CORS import json import pickle import nltk from nltk.corpus import stopwords import re from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.multiclass import OneVsRestClassifier from sklearn.metrics import f1_score import requests from string import punctuation app = Flask(__name__) CORS(app) app.config['JSON_AS_ASCII'] = False with open('YaTranslateKey.key', 'r') as file: auth = file.read().replace('\n', '') #reading api key for machine translation of texts # functions that read pickled ml models def load_classifier(): classifier = pickle.load(open('models/multilabel_model.sav', 'rb')) return classifier def load_tfidf(): tfidf = pickle.load(open('models/tfidf.sav', 'rb')) return tfidf def load_binarizer(): binarizer = pickle.load(open('models/multilabel_binarizer.sav', 'rb')) return binarizer # functions that preprocess text def clean_text(text): text = re.sub("\'", "", text) text = re.sub("[^a-zA-Z]", " ", text) text = ' '.join(text.split()) text = text.lower() return text wordnet_lemmatizer = WordNetLemmatizer() def lemmatize_text(text): lemmatized_text = [] sentence_words = nltk.word_tokenize(text) for word in sentence_words: lemmatized_text.append(wordnet_lemmatizer.lemmatize(word, pos="v")) lemmatized_text = ' '.join(lemmatized_text) return lemmatized_text nltk.download('stopwords') nltk.download('wordnet') nltk.download('punkt') stop_words = set(stopwords.words('english')) def remove_stopwords(text): no_stopword_text = [w for w in text.split() if not w in stop_words] return ' '.join(no_stopword_text) # main endpoint @app.route('/predict', methods=['POST']) def predict(): global auth #using yandex.translate api key request_json = request.get_json() x = str(request_json['input']) string = 'https://translate.yandex.net/api/v1.5/tr.json/translate?key=' + \ auth + '&text=' + x + '&lang=ru-en' r = requests.get(string) text = r.text[36:] #quick hack used instead of parsing ya.translate json text = text.strip('"]}') #quick hack used instead of parsing ya.translate json text = re.sub(",", "", text) x = text print(x) #print for heroku logs classifier = load_classifier() tfidf = load_tfidf() binarizer = load_binarizer() x = clean_text(x) x = remove_stopwords(x) x = lemmatize_text(x) q_vec = tfidf.transform([x]) q_pred = classifier.predict_proba(q_vec) #getting probabilities of all labels for given recipe text suggested_labels = [] counter = 0 for x in binarizer.classes_: #leaving only labels that have probabilities more than 0.75% proba = round(q_pred[0][counter], 2) if proba > 0.75: suggested_labels.append(str(x)) counter += 1 prediction = suggested_labels prediction = str(prediction).strip('[()]').replace("'", "") print('prediction:' + prediction) #print for heroku logs prediction = prediction.split(", ") response = json.dumps({'response': prediction}, ensure_ascii=False) return response, 200 #sending response to frontend if __name__ == '__main__': application.run(debug=True)
85b41744e676abe029670ad804a5c3af51b7e8b2
[ "Python" ]
1
Python
Sandy4321/recipes-classifier
75251910675554074e12b3aa2f52e79856bd6292
843f5faab38e4293d5b011d48c52a731bed7e3b9
refs/heads/master
<file_sep> var times = [["Monday","Wednesday"],[11,11],[13,13]]; function weekStartDay() { var startOfWeek = moment().startOf('isoWeek').format("MMMM Do"); document.getElementById("title").innerHTML += " " + startOfWeek; } function dispTrains() { var getTimeTable = document.getElementById('timeTable'); for (var i=0, row; row=getTimeTable.rows[i], i < 1; i++) { for (var j=0, col; col=row.cells[j]; j++) { getTimeTable.rows[i].cells[j].innerHTML = times[i][j]; } } for (var i=1, row; row=getTimeTable.rows[i]; i++) { for (var j=0, col; col=row.cells[j]; j++) { getTimeTable.rows[i].cells[j].innerHTML = times[i][j] + "-" + (times[i+1][j]-12); } } } function summarize() { //No trains today if (times[0].indexOf(moment().format("dddd"))===-1) { document.getElementById("cryptic").innerHTML = "The trains aren't running right now!"; document.getElementById("clarity").innerHTML = "(that means no office hours today)"; } else {//it's a day when office hours are held if (moment().hour() < times[1][0]) {//too early document.getElementById("cryptic").innerHTML = "You're early! The trains haven't arrived yet."; document.getElementById("clarity").innerHTML = "(that means I'm not in my office yet)"; $("body").css("background-image", "url(no_train_animated.gif)"); } else if (moment().hour() >= times[2][0]){ //too late console.log('bump at 38'); document.getElementById("cryptic").innerHTML = "The trains have departed already!"; document.getElementById("clarity").innerHTML = "(that means you've missed office hours)"; $("body").css("background-image", "url(depart_animated.gif)"); //wait setTimeout( function() { $("body").css("background-image", "url(no_train_animated.gif)"); }, 10550); } else { var boardStr = "Morrill Hall"; var boardStrLink = boardStr.link("http://www.umd.edu/CampusMaps/bld_detail.cfm?bld_code=MOR"); document.getElementById("cryptic").innerHTML = "The trains are currently boarding! Catch Vikash at 1102 " + boardStrLink + "."; document.getElementById("clarity").innerHTML = "(that means I'm in my office)"; $("body").css("background-image", "url(arrive_animation_stop.gif)"); } } }<file_sep># trainStation A page for my office hours at the University of Maryland
b28f363c0d3a91194c50b74e648c342eb95429aa
[ "JavaScript", "Markdown" ]
2
JavaScript
vikashsahu/trainStation
20ccf4c7535dbd6381ba5fb7d3e8fbc72dc5a664
5301f4090a57942de346ca7f6335e069c8b998e9
refs/heads/main
<repo_name>imdrashti/flashcard<file_sep>/main.py from tkinter import * import pandas import random BACKGROUND_COLOR = "#B1DDC6" # ---------------------------------CREATING NEW FLASHCARDS----------------------------------- data = pandas.read_csv("data_french_words.csv") data_dict = data.to_dict(orient="records") print(data_dict) current_card = {} def next_word(): global current_card current_card = random.choice(data_dict) print(current_card["French"]) canvas.itemconfig(card_title, text="French") canvas.itemconfig(card_word, text=current_card["French"]) # to change to english meaning of the french word def flip_card(): canvas.itemconfig(card_title, text="English") canvas.itemconfig(card_word, text=current_card["English"]) canvas.itemconfig(card_background, file="images_card_back.png") #------------------------------------UI SETUP---------------------------- window = Tk() window.title("Flash Card Game") # window.minsize(width=900, height=600) window.config(padx=50, pady=50, bg=BACKGROUND_COLOR) window.after(3000, func=flip_card) # image canvas = Canvas(width=800, height=526, bg=BACKGROUND_COLOR, highlightthickness=0) card_front_image = PhotoImage(file="images_card_front.png") card_back_image = PhotoImage(file="images_card_back.png") card_background = canvas.create_image(400, 263, image=card_front_image) card_title = canvas.create_text(400, 150, text="Title", font=("Arial", 40, "italic")) card_word = canvas.create_text(400, 263, text="word", font=("Arial", 60, "bold")) canvas.grid(column=0, row=0, columnspan=2) cross_image = PhotoImage(file="images_wrong.png") unknown_button = Button(image=cross_image, highlightthickness=0, command=next_word) unknown_button.grid(row=1, column=0) check_image = PhotoImage(file="images_right.png") known_button = Button(image=check_image, highlightthickness=0, command=next_word) known_button.grid(row=1, column=1) next_word() window.mainloop()
58b8ec122e69f91655fd5b439f1f894dd83b4a30
[ "Python" ]
1
Python
imdrashti/flashcard
265d3ae473f277f0c19f0e24a606d30395f8030b
83e752359e1ea8658dd34d9e70c8f5b51cfcb8de
refs/heads/master
<repo_name>lgarvey/cf-python-client<file_sep>/integration/test_service_instances.py import logging import unittest from config_test import build_client_from_configuration _logger = logging.getLogger(__name__) class TestServiceInstances(unittest.TestCase): def test_create_update_delete(self): client = build_client_from_configuration() result = client.service_instances.create(client.space_guid, 'test_name', client.plan_guid, client.creation_parameters) if len(client.update_parameters) > 0: client.service_instances.update(result['metadata']['guid'], client.update_parameters) else: _logger.warning('update test skipped') client.service_instances.remove(result['metadata']['guid']) def test_get(self): client = build_client_from_configuration() cpt = 0 for instance in client.service_instances.list(): if cpt == 0: self.assertIsNotNone( client.service_instances.get_first(space_guid=instance['entity']['space_guid'])) self.assertIsNotNone( client.service_instances.get(instance['metadata']['guid'])) self.assertIsNotNone( client.service_instances.list_permissions(instance['metadata']['guid'])) cpt += 1 _logger.debug('test_get - %d found', cpt) <file_sep>/test/imported.py import sys if sys.version_info.major == 2: from mock import patch, call, MagicMock from httplib import SEE_OTHER, CREATED, NO_CONTENT elif sys.version_info.major == 3: from unittest.mock import patch, call, MagicMock from http.client import SEE_OTHER, CREATED, NO_CONTENT else: raise ImportError('Invalid major version: %d' % sys.version_info.major)<file_sep>/test/test_loggregator.py import unittest from abstract_test_case import AbstractTestCase from cloudfoundry_client.imported import OK, reduce from fake_requests import mock_response class TestLoggregator(unittest.TestCase, AbstractTestCase): @classmethod def setUpClass(cls): cls.mock_client_class() def setUp(self): self.build_client() def test_recents(self): boundary = '7e061f8d6ec00677d6f6b17fcafec9eef2e3a2360e557f72e3e1116efcec' self.client.get.return_value = mock_response('/recent?app=app_id', OK, {'content-type': 'multipart/x-protobuf; boundary=%s' % boundary}, 'recents', 'GET_response.bin') cpt = reduce(lambda increment, _: increment + 1, self.client.loggregator.get_recent('app_id'), 0) self.client.get.assert_called_with(self.client.get.return_value.url, stream=True) self.assertEqual(cpt, 5946) <file_sep>/main/cloudfoundry_client/client.py from cloudfoundry_client.imported import OK, UNAUTHORIZED import logging import requests from oauth2_client.credentials_manager import CredentialManager, ServiceInformation from cloudfoundry_client.entities import InvalidStatusCode, EntityManager from cloudfoundry_client.v2.apps import AppManager from cloudfoundry_client.v2.buildpacks import BuildpackManager from cloudfoundry_client.v2.service_bindings import ServiceBindingManager from cloudfoundry_client.v2.service_brokers import ServiceBrokerManager from cloudfoundry_client.v2.service_instances import ServiceInstanceManager from cloudfoundry_client.v2.service_keys import ServiceKeyManager from cloudfoundry_client.v2.service_plans import ServicePlanManager _logger = logging.getLogger(__name__) class CloudFoundryClient(CredentialManager): def __init__(self, target_endpoint, client_id='cf', client_secret='', proxy=None, skip_verification=False): info = self.get_info(target_endpoint, proxy, skip_verification) if not info['api_version'].startswith('2.'): raise AssertionError('Only version 2 is supported for now. Found %s' % info['api_version']) service_informations = ServiceInformation(None, '%s/oauth/token' % info['authorization_endpoint'], client_id, client_secret, [], skip_verification) super(CloudFoundryClient, self).__init__(service_informations, proxy) self.service_plans = ServicePlanManager(target_endpoint, self) self.service_instances = ServiceInstanceManager(target_endpoint, self) self.service_keys = ServiceKeyManager(target_endpoint, self) self.service_bindings = ServiceBindingManager(target_endpoint, self) self.service_brokers = ServiceBrokerManager(target_endpoint, self) self.apps = AppManager(target_endpoint, self) self.buildpacks = BuildpackManager(target_endpoint, self) # Default implementations self.organizations = EntityManager(target_endpoint, self, '/v2/organizations') self.spaces = EntityManager(target_endpoint, self, '/v2/spaces') self.services = EntityManager(target_endpoint, self, '/v2/services') self.routes = EntityManager(target_endpoint, self, '/v2/routes') self._loggregator_endpoint = info.get('logging_endpoint', None) self._loggregator = None @property def loggregator(self): if self._loggregator is None: if self._loggregator_endpoint is None: raise NotImplementedError('No loggregator endpoint for this instance') else: from cloudfoundry_client.loggregator.loggregator import LoggregatorManager self._loggregator = LoggregatorManager(self._loggregator_endpoint, self) return self._loggregator @staticmethod def get_info(target_endpoint, proxy=None, skip_verification=False): # to get loggregator url info_response = requests.get('%s/v2/info' % target_endpoint, proxies=proxy if proxy is not None else dict(http='', https=''), verify=not skip_verification) if info_response.status_code != OK: raise InvalidStatusCode(info_response.status_code, info_response.text) info = info_response.json() return info @staticmethod def _is_token_expired(response): if response.status_code == UNAUTHORIZED: try: json_data = response.json() result = json_data.get('code', 0) == 1000 and json_data.get('error_code', '') == 'CF-InvalidAuthToken' _logger.info('_is_token_expired - %s' % str(result)) return result except: return False else: return False @staticmethod def _token_request_headers(_): return dict(Accept='application/json') <file_sep>/main/cloudfoundry_client/main.py #!/usr/bin/python import argparse import logging import os import re import sys import json from requests.exceptions import ConnectionError from cloudfoundry_client.imported import NOT_FOUND from cloudfoundry_client import __version__ from cloudfoundry_client.client import CloudFoundryClient from cloudfoundry_client.entities import InvalidStatusCode __all__ = ['main', 'build_client_from_configuration'] _logger = logging.getLogger(__name__) def _read_value_from_user(prompt, error_message=None, validator=None, default=''): while True: sys.stdout.write('%s [%s]: ' % (prompt, default)) sys.stdout.flush() answer_value = sys.stdin.readline().rstrip(' \r\n') if len(answer_value) == 0: answer_value = default if len(answer_value) > 0 and (validator is None or validator(answer_value)): return answer_value else: if error_message is None: sys.stderr.write('\"%s\": invalid value\n' % answer_value) else: sys.stderr.write('\"%s\": %s\n' % (answer_value, error_message)) def build_client_from_configuration(previous_configuration=None): dir_conf = os.path.join(os.path.expanduser('~')) if not os.path.isdir(dir_conf): if os.path.exists(dir_conf): raise IOError('%s exists but is not a directory') os.mkdir(dir_conf) config_file = os.path.join(dir_conf, '.cf_client_python.json') if not os.path.isfile(config_file): target_endpoint = _read_value_from_user('Please enter a target endpoint', 'Url must starts with http:// or https://', lambda s: s.startswith('http://') or s.startswith('https://'), default='' if previous_configuration is None else previous_configuration.get('target_endpoint', '')) skip_ssl_verification = _read_value_from_user('Skip ssl verification (true/false)', 'Enter either true or false', lambda s: s == 'true' or s == 'false', default='false' if previous_configuration is None else json.dumps( previous_configuration.get('skip_ssl_verification', False))) login = _read_value_from_user('Please enter your login') password = _read_value_from_user('Please enter your password') client = CloudFoundryClient(target_endpoint, skip_verification=(skip_ssl_verification == 'true')) client.init_with_user_credentials(login, password) with open(config_file, 'w') as f: f.write(json.dumps(dict(target_endpoint=target_endpoint, skip_ssl_verification=(skip_ssl_verification == 'true'), refresh_token=client.refresh_token), indent=2)) return client else: try: configuration = None with open(config_file, 'r') as f: configuration = json.load(f) client = CloudFoundryClient(configuration['target_endpoint'], skip_verification=configuration['skip_ssl_verification']) client.init_with_token(configuration['refresh_token']) return client except Exception as ex: if type(ex) == ConnectionError: raise else: _logger.exception("Could not restore configuration. Cleaning and recreating") os.remove(config_file) return build_client_from_configuration(configuration) def is_guid(s): return re.match(r'[\d|a-z]{8}-[\d|a-z]{4}-[\d|a-z]{4}-[\d|a-z]{4}-[\d|a-z]{12}', s.lower()) is not None def resolve_id(argument, get_by_name, domain_name, allow_search_by_name): if is_guid(argument): return argument elif allow_search_by_name: result = get_by_name(argument) if result is not None: return result['metadata']['guid'] else: raise InvalidStatusCode(NOT_FOUND, '%s with name %s' % (domain_name, argument)) else: raise ValueError('id: %s: does not allow search by name' % domain_name) def log_recent(client, application_guid): for message in client.loggregator.get_recent(application_guid): _logger.info(message.message) def _get_client_domain(client, domain): return getattr(client, '%ss' % domain) def main(): logging.basicConfig(level=logging.INFO, format='%(message)s') logging.getLogger("requests").setLevel(logging.WARNING) logging.getLogger("urllib3").setLevel(logging.WARNING) commands = dict() commands['organization'] = dict(list=(), name='name', allow_retrieve_by_name=True, allow_creation=True, allow_deletion=True, display_name='Organizations') commands['space'] = dict(list=('organization_guid',), name='name', allow_retrieve_by_name=True, allow_creation=True, allow_deletion=True, display_name='Spaces') commands['app'] = dict(list=('organization_guid', 'space_guid',), name='name', allow_retrieve_by_name=True, allow_creation=True, allow_deletion=True, display_name='Applications') commands['service'] = dict(list=('service_broker_guid',), name='label', allow_retrieve_by_name=True, allow_creation=True, allow_deletion=True, display_name='Services') commands['service_plan'] = dict(list=('service_guid', 'service_instance_guid', 'service_broker_guid'), name='name', allow_retrieve_by_name=False, allow_creation=False, allow_deletion=False, display_name='Service plans') commands['service_instance'] = dict(list=('organization_guid', 'space_guid', 'service_plan_guid'), name='name', allow_retrieve_by_name=False, allow_creation=True, allow_deletion=True, display_name='Service instances') commands['service_key'] = dict(list=('service_instance_guid',), name='name', allow_retrieve_by_name=False, allow_creation=True, allow_deletion=True, display_name='Service keys') commands['service_binding'] = dict(list=('app_guid', 'service_instance_guid'), name=None, allow_retrieve_by_name=False, allow_creation=True, allow_deletion=True, display_name='Service bindings') commands['service_broker'] = dict(list=('name', 'space_guid'), name='name', allow_retrieve_by_name=True, allow_creation=True, allow_deletion=True, display_name='Service brokers') commands['buildpack'] = dict(list=(), name='name', allow_retrieve_by_name=False, allow_creation=False, allow_deletion=False, display_name='Buildpacks') commands['route'] = dict(list=(), name='host', allow_retrieve_by_name=False, allow_creation=False, allow_deletion=False, display_name='Routes') application_commands = dict(recent_logs=('get_recent_logs', 'Recent Logs',), env=('get_env', 'Get the environment of an application',), instances=('get_instances', 'Get the instances of an application',), stats=('get_stats', 'Get the stats of an application',), summary=('get_summary', 'Get the summary of an application',), start=('start', 'Start an application',), stop=('stop', 'Stop an application',)) application_extra_list_commands = dict(routes=('list_routes', 'List the routes(host) of an application', 'host')) description = [] for domain, command_description in list(commands.items()): description.append(' %s' % command_description['display_name']) description.append(' list_%ss : List %ss' % (domain, domain)) description.append(' get_%s : Get a %s by %s' % (domain, domain, 'UUID or name (first found then)' if command_description['allow_retrieve_by_name'] else 'UUID')) if command_description['allow_creation']: description.append(' create_%s : Create a %s' % (domain, domain)) if command_description['allow_deletion']: description.append(' delete_%s : Delete a %s' % (domain, domain)) if domain == 'application': for command, application_command_description in list(application_commands.items()): description.append(' %s : %s' % (command, application_command_description[1])) for command, application_command_description in list(application_extra_list_commands.items()): description.append(' %s : %s' % (command, application_command_description[1])) description.append('') parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('-V', '--version', action='version', version=__version__) subparsers = parser.add_subparsers(title='Commands', dest='action', description='\n'.join(description)) for domain, command_description in list(commands.items()): list_parser = subparsers.add_parser('list_%ss' % domain) for filter_parameter in command_description['list']: list_parser.add_argument('-%s' % filter_parameter, action='store', dest=filter_parameter, type=str, default=None, help='Filter with %s' % filter_parameter) get_parser = subparsers.add_parser('get_%s' % domain) get_parser.add_argument('id', metavar='ids', type=str, nargs=1, help='The id. Can be UUID or name (first found then)' if command_description['allow_retrieve_by_name'] else 'The id (UUID)') if command_description['allow_creation']: create_parser = subparsers.add_parser('create_%s' % domain) create_parser.add_argument('entity', metavar='entities', type=str, nargs=1, help='Either a path of the json file containing the %s or a json object or the json %s object' % (domain, domain)) if command_description['allow_deletion']: delete_parser = subparsers.add_parser('delete_%s' % domain) delete_parser.add_argument('id', metavar='ids', type=str, nargs=1, help='The id. Can be UUID or name (first found then)' if command_description['allow_retrieve_by_name'] else 'The id (UUID)') if domain == 'app': for command, application_command_description in list(application_commands.items()): command_parser = subparsers.add_parser(command) command_parser.add_argument('id', metavar='ids', type=str, nargs=1, help='The id. Can be UUID or name (first found then)') for command, application_command_description in list(application_extra_list_commands.items()): command_parser = subparsers.add_parser(command) command_parser.add_argument('id', metavar='ids', type=str, nargs=1, help='The id. Can be UUID or name (first found then)') arguments = parser.parse_args() client = build_client_from_configuration() if arguments.action == 'recent_logs': resource_id = resolve_id(arguments.id[0], lambda x: client.apps.get_first(name=x), 'application', True) log_recent(client, resource_id) elif application_commands.get(arguments.action) is not None: resource_id = resolve_id(arguments.id[0], lambda x: client.apps.get_first(name=x), 'application', True) print(getattr(client.apps, application_commands[arguments.action][0])(resource_id).json(indent=1)) elif application_extra_list_commands.get(arguments.action) is not None: resource_id = resolve_id(arguments.id[0], lambda x: client.apps.get_first(name=x), 'application', True) name_property = application_extra_list_commands[arguments.action][2] for entity in getattr(client.apps, application_extra_list_commands[arguments.action][0])(resource_id): print('%s - %s' % (entity['metadata']['guid'], entity['entity'][name_property])) elif arguments.action.find('list_') == 0: domain = arguments.action[len('list_'): len(arguments.action) - 1] filter_list = dict() for filter_parameter in commands[domain]['list']: filter_value = getattr(arguments, filter_parameter) if filter_value is not None: filter_list[filter_parameter] = filter_value for entity in _get_client_domain(client, domain).list(**filter_list): name_property = commands[domain]['name'] if name_property is not None: print('%s - %s' % (entity['metadata']['guid'], entity['entity'][name_property])) else: print(entity['metadata']['guid']) elif arguments.action.find('get_') == 0: domain = arguments.action[len('get_'):] resource_id = resolve_id(arguments.id[0], lambda x: _get_client_domain(client, domain).get_first( **{commands[domain]['name']: x}), domain, commands[domain]['allow_retrieve_by_name']) print(_get_client_domain(client, domain).get(resource_id).json(indent=1)) elif arguments.action.find('create_') == 0: domain = arguments.action[len('create_'):] data = None if os.path.isfile(arguments.entity[0]): with open(arguments.entity[0], 'r') as f: try: data = json.load(f) except ValueError: raise ValueError('entity: file %s does not contain valid json data' % arguments.entity[0]) else: try: data = json.loads(arguments.entity[0]) except ValueError: raise ValueError('entity: must be either a valid json file path or a json object') print(_get_client_domain(client, domain)._create(data).json()) elif arguments.action.find('delete_') == 0: domain = arguments.action[len('delete_'):] if is_guid(arguments.id[0]): _get_client_domain(client, domain)._remove(arguments.id[0]) elif commands[domain]['allow_retrieve_by_name']: filter_get = dict() filter_get[commands[domain]['name']] = arguments.id[0] entity = _get_client_domain(client, domain).get_first(**filter_get) if entity is None: raise InvalidStatusCode(NOT_FOUND, '%s with name %s' % (domain, arguments.id[0])) else: _get_client_domain(client, domain)._remove(entity['metadata']['guid']) else: raise ValueError('id: %s: does not allow search by name' % domain) if __name__ == "__main__": main() <file_sep>/README.rst Cloudfoundry python client ========================== .. image:: https://img.shields.io/pypi/v/cloudfoundry-client.svg :target: https://pypi.python.org/pypi/cloudfoundry-client .. image:: https://img.shields.io/github/license/antechrestos/cf-python-client.svg :target: https://raw.githubusercontent.com/antechrestos/cf-python-client/master/LICENSE The cf-python-client repo contains a Python client library for Cloud Foundry. Installing ---------- From pip ~~~~~~~~ .. code-block:: bash $ pip install cloudfoundry-client From sources ~~~~~~~~~~~~ To build the library run : .. code-block:: bash $ python setup.py install Run the client -------------- To run the client, enter the following command : .. code-block:: bash $ cloudfoundry-client This will explains you how the client works. At first execution, it will ask you information about the platform you want to reach (url, login and so on). Please note that your credentials won't be saved on your disk: only tokens will be kept for further use. Use the client in your code --------------------------- You may build the client and use it in your code Client ~~~~~~ To instanciate the client, nothing easier .. code-block:: python from cloudfoundry_client.client import CloudFoundryClient target_endpoint = 'https://somewhere.org' proxy = dict(http=os.environ.get('HTTP_PROXY', ''), https=os.environ.get('HTTPS_PROXY', '')) client = CloudFoundryClient(target_endpoint, proxy=proxy, skip_verification=True) client.init_with_user_credentials('login', 'password') And then you can use it as follows: .. code-block:: python for organization in client.organizations: print organization['metadata']['guid'] Entities ~~~~~~~~ Entities returned by client calls (*organization*, *space*, *app*..) are navigable ie you can call the method associated with the *xxx_url* entity attribute (note that if the attribute's name ends with a list, it will be interpreted as a list of object. Other wise you will get a single entity). .. code-block:: python for organization in client.organizations: for space in organization.spaces(): # perform a GET on spaces_url attribute organization_reloaded = space.organization() # perform a GET on organization_url attribute Application object provides more methods such as - instances - stats - start - stop - summary As instance, you can get all the summaries as follows: Or else: .. code-block:: python for app in client.apps: print app.summary() Available managers ~~~~~~~~~~~~~~~~~~ So far the implemented managers that are available are: - ``service_plans`` - ``service_instances`` - ``service_keys`` - ``service_bindings`` - ``service_brokers`` - ``apps`` - ``buildpacks`` - ``organizations`` - ``spaces`` - ``services`` - ``routes`` Note that even if, while navigating, you reach an entity manager that does not exist, the get will be performed and you will get the expected entities. For example, event entity manager is not yet implemented but you can do .. code-block:: python for app in client.apps: for event in app.events(): handle_event_object() All managers provide the following methods: - ``list(**kwargs)``: return an *iterator* on entities, according to the given filtered parameters - ``get_first(**kwargs)``: return the first matching entity according to the given parameters. Returns ```None`` if none returned - ``get``: perform a **GET** on the entity. If the entity cannot be find it will raise an exception due to http *NOT FOUND* response status - ``__iter__``: iteration on the manager itself. Alias for a no-filter list - ``__getitem__``: alias for the ``get`` operation - ``_create``: the create operation. Since it is a generic operation (only takes a *dict* object), this operation is protected - ``_update``: the update operation. Since it is a generic operation (only takes a the resource id and a *dict* object), this operation is protected - ``_remove``: the delete operation. This operation is maintained protected. Command Line Interface ---------------------- The client comes with a command line interface. Run ``cloudfoundry-client`` command. At first execution, it will ask you information about the target platform and your credential (do not worry they are not saved). After that you may have a help by running ``cloudfoundry-client -h`` Issues and contributions ------------------------ Please submit issue/pull request. <file_sep>/main/cloudfoundry_client/loggregator/loggregator.py import logging import re from cloudfoundry_client.loggregator.logmessage_pb2 import LogMessage from cloudfoundry_client.entities import EntityManager _logger = logging.getLogger(__name__) class InvalidLoggregatorResponseException(Exception): pass class LoggregatorManager(object): def __init__(self, logging_endpoint, credentials_manager): self.logging_endpoint = logging_endpoint self.credentials_manager = credentials_manager def get_recent(self, application_guid): url = '%s/recent?app=%s' % (re.sub(r'^ws', 'http', self.logging_endpoint), application_guid) response = EntityManager._check_response(self.credentials_manager.get(url, stream=True)) boundary = LoggregatorManager._extract_boundary(response) for part in LoggregatorManager._read_multi_part_response(response, boundary): message_read = LogMessage() message_read.ParseFromString(part) yield message_read @staticmethod def _extract_boundary(response): boundary = response.headers['content-type'] boundary_field = 'boundary=' idx = boundary.find(boundary_field) if idx == -1: _logger.debug(response.text) raise InvalidLoggregatorResponseException('Cannot extract boundary in %s' % boundary) boundary = boundary[idx + len(boundary_field):] idx = boundary.find(' ') if idx != -1: boundary = boundary[:idx] return boundary @staticmethod def _read_multi_part_response(iterable, boundary): remaining = '' boundary_header = '--%s' % boundary cpt_read = 0 for chunk_data in iterable: # _logger.debug('reading %d bytes' % size) cpt_read += len(chunk_data) if len(chunk_data) == 0: # _logger.debug('end of file reached after %d bytes' % cpt_read) if len(remaining) > 0: # _logger.debug('returning last data') yield remaining return else: work = remaining + chunk_data if len(remaining) > 0 else chunk_data idx = work.find(boundary_header) while idx >= 0 and (idx + len(boundary_header) + 2) <= len(work): # _logger.debug('found boundary in %d byte', (cpt_read - (len(work) - idx))) if idx > 0: part = work[:idx] # do not use rstrip or lstrip while part.find('\r\n', 0, 2) == 0: part = part[2:] while part.rfind('\r\n', len(part) - 2) == (len(part) - 2): part = part[0:len(part) - 2] yield part work = work[idx + len(boundary_header):] if work[0] == '-' and work[1] == '-': _logger.debug('end boundary reached') return else: idx = work.find(boundary_header) remaining = work <file_sep>/main/cloudfoundry_client/v2/apps.py import logging from time import sleep from cloudfoundry_client.imported import BAD_REQUEST from cloudfoundry_client.entities import JsonObject, Entity, EntityManager, InvalidStatusCode _logger = logging.getLogger(__name__) class _Application(Entity): def instances(self): return self.client.apps.get_instances(self['metadata']['guid']) def start(self): return self.client.apps.start(self['metadata']['guid']) def stop(self): return self.client.apps.stop(self['metadata']['guid']) def stats(self): return self.client.apps.get_stats(self['metadata']['guid']) def summary(self): return self.client.apps.get_summary(self['metadata']['guid']) class AppManager(EntityManager): def __init__(self, target_endpoint, client): super(AppManager, self).__init__(target_endpoint, client, '/v2/apps', lambda pairs: _Application(target_endpoint, client, pairs)) def get_stats(self, application_guid): return self._get('%s/%s/stats' % (self.entity_uri, application_guid), JsonObject) def get_instances(self, application_guid): return self._get('%s/%s/instances' % (self.entity_uri, application_guid), JsonObject) def get_env(self, application_guid): return self._get('%s/%s/env' % (self.entity_uri, application_guid), JsonObject) def get_summary(self, application_guid): return self._get('%s/%s/summary' % (self.entity_uri, application_guid), JsonObject) def list_routes(self, application_guid, **kwargs): return self.client.routes._list('%s/%s/routes' % (self.entity_uri, application_guid), **kwargs) def list_service_bindings(self, application_guid, **kwargs): return self.client.service_bindings._list('%s/%s/service_bindings' % (self.entity_uri, application_guid), **kwargs) def start(self, application_guid, check_time=0.5, timeout=300, async=False): result = super(AppManager, self)._update(application_guid, dict(state='STARTED')) if async: return result else: summary = self.get_summary(application_guid) self._wait_for_instances_in_state(application_guid, summary['instances'], 'RUNNING', check_time, timeout) return result def stop(self, application_guid, check_time=0.5, timeout=500, async=False): result = super(AppManager, self)._update(application_guid, dict(state='STOPPED')) if async: return result else: self._wait_for_instances_in_state(application_guid, 0, 'STOPPED', check_time, timeout) return result def _wait_for_instances_in_state(self, application_guid, number_required, state_expected, check_time, timeout): all_in_expected_state = False sum_waiting = 0 while not all_in_expected_state: instances = self._safe_get_instances(application_guid) number_in_expected_state = 0 for instance_number, instance in list(instances.items()): if instance['state'] == state_expected: number_in_expected_state += 1 # this case will make this code work for both stop and start operation all_in_expected_state = number_in_expected_state == number_required if not all_in_expected_state: _logger.debug('_wait_for_instances_in_state - %d/%d %s', number_in_expected_state, number_required, state_expected) if sum_waiting > timeout: raise AssertionError('Failed to get state %s for %d instances' % (state_expected, number_required)) sleep(check_time) sum_waiting += check_time def _safe_get_instances(self, application_guid): try: return self.get_instances(application_guid) except InvalidStatusCode as ex: if ex.status_code == BAD_REQUEST and type(ex.body) == dict: code = ex.body.get('code', -1) # 170002: staging not finished # 220001: instances error if code == 220001 or code == 170002: return {} else: _logger.error("") raise <file_sep>/requirements.txt protobuf==3.6.0 oauth2-client==0.0.21
45c6e2df0f57fd3a26071a75d0a03a028e3ff149
[ "Python", "Text", "reStructuredText" ]
9
Python
lgarvey/cf-python-client
37fc3386eb7b853e715b3c50d964505075d587ff
d1287eb4cf78fed6da6a908e3c37ba77425d262b
refs/heads/master
<repo_name>neperz/Guiders-JS<file_sep>/guidersNew.js var DIALOG_SHOWN_CLASS = "dialog-shown", DISABLED_CLASS = "disabled", ERROR_CLASS = "error", EXPANDED_CLASS = "expanded", MENU_OVERLAY_CLASS = "menu-overlay", ORIGINAL_CLASS = "original", SELECTED_CLASS = "selected", SHOW_CLASS = "show", SUCCESS_CLASS = "success", UI_EFFECT_DURATION = 300, UI_EFFECT_DURATION_LONG = 800, UI_EFFECT_DURATION_SHORT = 100, UI_EFFECT_EASING_IN = "easeInExpo", UI_EFFECT_EASING_OUT = "easeOutExpo", fadingHtmlChange = function (a, b, c, d) { a.is(":animated") ? a.data("fadingHtmlChangeNewHtml", b) : a.html() !== b && (c = c || UI_EFFECT_DURATION, a.fadeOut(c, UI_EFFECT_EASING_OUT, function () { var e = a.data("fadingHtmlChangeNewHtml") || b; a.html(e).fadeIn(c, UI_EFFECT_EASING_OUT, d); a.removeData("fadingHtmlChangeNewHtml") })) }, getElementMidpoint = function (a) { var b = a.offset(); return { x: b.left + Math.floor(a[0].offsetWidth / 2), y: b.top + Math.floor(a[0].offsetHeight / 2) } }, tempFadingHtmlChange = function (a, b, c, d, e) { var c = c || 3E3, f = a.data("tempFadingHtmlChangeTimeoutId"), g = a.data("tempFadingHtmlChangeOriginalHtml") || a.html(); f && clearTimeout(f); fadingHtmlChange(a, b, d); f = setTimeout(function () { var b = a.data("tempFadingHtmlChangeOriginalHtml"); b && (fadingHtmlChange(a, b, d, e), a.removeData("tempFadingHtmlChangeOriginalHtml"), a.removeData("tempFadingHtmlChangeTimeoutId")) }, c); a.data("tempFadingHtmlChangeOriginalHtml", g); a.data("tempFadingHtmlChangeTimeoutId", f) }; var optly = { Cleanse: {} }; optly.guider = {}; var guider = function () { var a = { _defaultSettings: { attachTo: null, buttons: [], buttonCustomHTML: "", description: "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", overlay: false, position: 0, title: "Sample title goes here", width: 400 }, _htmlSkeleton: "<div class='guider'> <div class='guider_content'> <h1 class='guider_title'></h1> <p class='guider_description'></p> <div class='guider_buttons'> </div> </div> <div class='guider_arrow'> </div></div>", _arrowSize: 42, _guiders: {}, _currentGuiderID: null, _lastCreatedGuiderID: null, _addButtons: function (b) { for (var c = b.buttons.length - 1; 0 <= c; c--) { var d = b.buttons[c], e = "<a class='guider_button"; "undefined" !== typeof d.classString && null !== d.classString && (e = e + " " + d.classString); e = e + "'>" + d.name + "</a>"; e = $(e); b.elem.find(".guider_buttons").append(e); if (d.onclick) { e.on("click", d.onclick); } else if (!d.onclick && "close" === d.name.toLowerCase()) { e.on("click", function () { a.hideAll(); }); } else if (!d.onclick && "next" === d.name.toLowerCase()) { e.on("click", function () { a.next(); }); } } "" !== b.buttonCustomHTML && (c = $(b.buttonCustomHTML), b.elem.find(".guider_buttons").append(c)); }, _attach: function (b) { if (!("undefined" === typeof b.attachTo || null === b)) { var c = b.elem.innerHeight(), d = b.elem.innerWidth(); b.attachToElem = $(b.attachTo); if (0 === b.attachToElem.length || 0 === b.position) { b.elem.css("position", "absolute"), b.elem.css("top", ($(window).height() - c) / 3.2 + $(window).scrollTop() + "px"), b.elem.css("left", ($(window).width() - d) / 2 + $(window).scrollLeft() + "px"); } else { var e = b.attachToElem.offset(), g = b.attachToElem.innerHeight(), i = b.attachToElem.innerWidth(), h = e.top, e = e.left, j = 0.9 * a._arrowSize; offset = { 1: [-j - c, i - d], 2: [0, j + i], 3: [g / 2 - c / 2, j + i], 4: [g - c, j + i], 5: [j + g, i - d], 6: [j + g, i / 2 - d / 2], 7: [j + g, 0], 8: [g - c, -d - j], 9: [g / 2 - c / 2, -d - j], 10: [0, -d - j], 11: [-j - c, 0], 12: [-j - c, i / 2 - d / 2] }[b.position]; h += offset[0]; e += offset[1]; b.elem.css({ position: "absolute", top: h, left: e }); } } }, _guiderById: function (b) { if ("undefined" === typeof a._guiders[b]) { throw "Cannot find guider with id " + b; } return a._guiders[b]; }, _showOverlay: function () { $("#guider_overlay").fadeIn(UI_EFFECT_DURATION); }, _hideOverlay: function () { $("#guider_overlay").fadeOut(UI_EFFECT_DURATION); }, _initializeOverlay: function () { 0 === $("#guider_overlay").length && $("<div id=\"guider_overlay\"></div>").hide().appendTo("body"); }, _styleArrow: function (b) { var c = b.position || 0; if (c) { var d = $(b.elem.find(".guider_arrow")); d.addClass({ 1: "guider_arrow_down", 2: "guider_arrow_left", 3: "guider_arrow_left", 4: "guider_arrow_left", 5: "guider_arrow_up", 6: "guider_arrow_up", 7: "guider_arrow_up", 8: "guider_arrow_right", 9: "guider_arrow_right", 10: "guider_arrow_right", 11: "guider_arrow_down", 12: "guider_arrow_down" }[c]); var c = b.elem.innerHeight(), e = b.elem.innerWidth(), g = a._arrowSize / 2, c = { 1: ["right", g], 2: ["top", g], 3: ["top", c / 2 - g], 4: ["bottom", g], 5: ["right", g], 6: ["left", e / 2 - g], 7: ["left", g], 8: ["bottom", g], 9: ["top", c / 2 - g], 10: ["top", g], 11: ["left", g], 12: ["left", e / 2 - g] }[b.position]; d.css(c[0], c[1] + "px"); } }, next: function () { var b = a._guiders[a._currentGuiderID]; if ("undefined" !== typeof b && (b = b.next || null, null !== b && "" !== b)) { var c = a._guiderById(b).overlay ? true : false; a.hideAll(c); a.show(b); } }, createGuider: function (b) { "object" !== $.type(b) && (b = {}); myGuider = $.extend(true, {}, a._defaultSettings, b); myGuider.id = myGuider.id || String(Math.floor(1000 * Math.random())); b = $(a._htmlSkeleton); myGuider.elem = b; myGuider.elem.css("width", myGuider.width + "px"); b.find("h1.guider_title").html(myGuider.title); b.find("p.guider_description").html(myGuider.description); a._addButtons(myGuider); b.hide(); b.appendTo("body"); "undefined" !== typeof myGuider.attachTo && null !== myGuider && (a._attach(myGuider), a._styleArrow(myGuider)); a._initializeOverlay(); a._guiders[myGuider.id] = myGuider; a._lastCreatedGuiderID = myGuider.id; return a; }, hideAll: function (b) { $(".guider").fadeOut("fast"); "undefined" !== typeof b && true === b || a._hideOverlay(); return a; }, show: function (b) { !b && a._lastCreatedGuiderID && (b = a._lastCreatedGuiderID); var c = a._guiderById(b); c.overlay && a._showOverlay(); a._attach(c); c.elem.fadeIn("fast"); a._currentGuiderID = b; return a; } }; return a; } .call(this);
15969ddc1f33965bed9b17f0c14283011b38f93f
[ "JavaScript" ]
1
JavaScript
neperz/Guiders-JS
e5018c1e041004de46f15c38ad9f4c11021b0222
c67d1ee5210c2951b1c4216946c44fffe7fa1bde
refs/heads/master
<file_sep>import React, { useEffect, useState } from "react"; import "../blog.css"; import backgroundPhoto from "../images/personal_site_background.jpg"; const Blog = () => { const [typedTextSpan, setTypedText] = useState(""); const [cursor, setCursor] = useState(false); const styles = { background: ` linear-gradient(to top, rgba(0, 0, 0,0.9) 20%, transparent),url(${backgroundPhoto})`, backgroundSize: "cover", backgroundPosition: "center", backgroundRepeat: "no-repeat", position: "relative", overflow: "hidden", }; const textArray = [ "Software Developer.", "Problem Solver.", "Programmer.", "Tech Enthusiast.", ]; const typingDelay = 200; const erasingDelay = 100; const newTextDelay = 1000; let textArrayIndex = 0; let charIndex = 0; let textSpanCopy = typedTextSpan; const type = () => { if (charIndex < textArray[textArrayIndex].length) { textSpanCopy += textArray[textArrayIndex].charAt(charIndex); setCursor(true); setTypedText(textSpanCopy); charIndex++; setTimeout(type, typingDelay); } else { setTimeout(erase, newTextDelay); } }; const erase = () => { if (charIndex > 0) { setTypedText(textArray[textArrayIndex].substring(0, charIndex - 1)); charIndex--; setTimeout(erase, erasingDelay); } else { textArrayIndex++; if (textArrayIndex >= textArray.length) textArrayIndex = 0; textSpanCopy = ""; setCursor(false); setTimeout(type, typingDelay + 1100); } }; // eslint-disable-next-line useEffect(() => { // eslint-disable-next-line setTimeout(type, 2000); // eslint-disable-next-line }, []); return ( <> <div style={styles}> <h1 className="title__message"> I am a <span className="typed-text">{typedTextSpan}</span> <span className={cursor ? "cursor typing" : "cursor"} style={{ fontStyle: "italic" }} > &nbsp; </span> </h1> <div className="welcome"> <h1>Hi there, I'm Liam!</h1> <p> I am a Software Developer with passion for learning and finding solutions to challenging problems. Checkout my <span> <a href="/projects">Portfolio</a> </span>{" "} to see what I have been working on or visit my <span> <a href="https://github.com/Li-Ri">Github</a> </span> . </p> </div> </div> </> ); }; export default Blog; <file_sep>import React from "react"; import "../App.css"; import github from "../images/git-logo.png"; import linked from "../images/linked.png"; import profilePic from "../images/profile_pic.png"; const NavBar = ({ showImg, setShowImg }) => { const handleHover = () => { setShowImg(!showImg); }; const handleLeave = () => { setShowImg(!showImg); }; return ( <header> <div className="header-title"> <h2 id="logo-title"><NAME></h2> <div className="profile-pic"> <img src={profilePic} alt="" /> </div> <h4 id="quote">Full Stack Engineer</h4> <div className="contact-info"> <p>Tel: +44 7801174094</p> <p>Email: <EMAIL></p> </div> </div> <nav className="main-nav"> <ul className="main-nav__items"> <li className="main-nav__item"> <a href="/">Home</a> </li> <li className="main-nav__item"> <a href="/projects" onMouseOver={handleHover} onMouseLeave={handleLeave} > Projects </a> </li> <li className="main-nav__item"> <a href="/about">Who am I?</a> </li> <li className="social-link"> <a href="https://github.com/Li-Ri"> <img src={github} alt="" /> </a> </li> <li className="social-link"> <a href="https://www.linkedin.com/in/liam-richens-516314144/"> <img src={linked} alt="" /> </a> </li> </ul> </nav> </header> ); }; export default NavBar; <file_sep>import crytoImg from "./images/crypto.png"; import gymImg from "./images/gymclub.png"; import planeImg from "./images/spaceplane.png"; import scrapbookImg from "./images/scrapbook.png"; const projects = [ { title: "Spaceplane Project", techStack: " | Python, NumPy, SciPy", about: "This project looks at spacecrafts in Low Earth Orbit using Rocket theory and Orbital Mechanics Optimizes the fuel requirements in order to reach a target orbit.", link: "https://github.com/Li-Ri/Spaceplane-Project", image: planeImg, }, { title: "CryptoBite", techStack: " | Express, React, MongoDB, Chart JS", about: "Crypto tracker that allows users to track the current trends in multiple currencies, add them to their portfolio and invest. This app also streams live data on the current and historical price on the coins to track overall portfolio performance with time.", link: "https://github.com/Li-Ri/Crypto_Wallet_React_App", image: crytoImg, }, { title: "ScrapBook", techStack: " | Java Spring, React, Web Sockets, Firebase", about: "Scrapbook is a social media app that allows users to create private rooms on their profile for groups to share content such as images and captioned posts as well live chat.", link: "https://github.com/Li-Ri/ScrapBook_Frontend", image: scrapbookImg, }, { title: "Gym Booking App", techStack: " | Python, Flask, JS, PostgreSQL", about: "A booking app to manage the classes that instructors and members are booked onto as well as managing customer and employee data", link: "https://github.com/Li-Ri/gym_app_Flask_Postgresql", image: gymImg, }, ]; export default projects; <file_sep>import React from "react"; const ProjectView = ({ project }) => { return ( <> <div className="project-desc"> <h1>{project.title}</h1> <img src={project.image} alt="" /> <p>{project.about}</p> </div> </> ); }; export default ProjectView; <file_sep>import NavBar from "./components/NavBar"; import { BrowserRouter as Router, Route, Switch } from "react-router-dom"; import About from "./components/About"; import Blog from "./components/Blog"; import Contact from "./components/Contact"; import Projects from "./components/Projects"; import ProjectView from "./components/ProjectView"; import React, { useState } from "react"; import "./App.css"; import projects from "./projectInfo"; function App() { const [showImg, setShowImg] = useState(false); return ( <div className="App grid-container"> <NavBar showImg={showImg} setShowImg={setShowImg} /> <Router> <Switch> <Route exact path="/" component={Blog} /> <Route path="/projects" component={Projects} /> <Route path="/about" component={About} /> <Route path="/contact" component={Contact} /> <Route path="/:index" render={(props) => { const index = props.match.params.index; const project = projects[index]; return <ProjectView project={project} />; }} /> </Switch> </Router> </div> ); } export default App;
614fe013501e03a81d5b86a704aa6bd59a073e04
[ "JavaScript" ]
5
JavaScript
Li-Ri/PersonalWebsite
a5d671ec047e53d051b19da18a5310f9aa8916f9
343850efecf43655383e6f2b6e6364eef83ce25f
refs/heads/master
<repo_name>jc-hsiao/Product-Inventory-Lab<file_sep>/src/main/java/models/Printer.java package models; public class Printer { private int id; private String name; private String brand; private String inkType; private boolean canConnectWifi; private boolean hasColorOutput; private boolean isForBusiness; public Printer() { } public Printer(int id, String name, String brand, String inkType, boolean canConnectWifi, boolean hasColorOutput, boolean isForBusiness) { this.id = id; this.name = name; this.brand = brand; this.inkType = inkType; this.canConnectWifi = canConnectWifi; this.hasColorOutput = hasColorOutput; this.isForBusiness = isForBusiness; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getInkType() { return inkType; } public void setInkType(String inkType) { this.inkType = inkType; } public boolean canWorkWithWifi() { return canConnectWifi; } public void setWifiConnectivity(boolean canConnectWifi) { this.canConnectWifi = canConnectWifi; } public boolean canPrintDifferentColor() { return hasColorOutput; } public void setColorOutputAbility(boolean hasColorOutput) { this.hasColorOutput = hasColorOutput; } public boolean canUseForBusiness() { return isForBusiness; } public void setBusinessAbility(boolean forBusiness) { isForBusiness = forBusiness; } } <file_sep>/src/main/java/services/PrinterService.java package services; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.sun.org.apache.xpath.internal.operations.Bool; import models.Printer; import java.io.*; import java.lang.reflect.Array; import java.util.*; public class PrinterService { private static int nextId = 1; private ArrayList<Printer> inventory = new ArrayList<>(); public Printer create(String name, String brand, String inkType, boolean canConnectWifi, boolean hasColorOutput, boolean isForBusiness) { Printer newPrinter = new Printer(nextId++,name, brand, inkType, canConnectWifi, hasColorOutput, isForBusiness); inventory.add(newPrinter); return newPrinter; } //read public Printer findPrinter(int id) { // should take an int and return an object with that id, if exists for(int i=0; i<inventory.size(); i++){ if(inventory.get(i).getId()==id){ return inventory.get(i); } } return null; } //read all public Printer[] findAll() { Printer[] a = new Printer[inventory.size()]; for(int i=0; i<inventory.size(); i++){ a[i] = inventory.get(i); } return a; } //delete public boolean delete(int id) { // should remove the object with this id from the ArrayList if exits and return true. // Otherwise return false if(findPrinter(id) != null){ inventory.remove(findPrinter(id)); return true; }else{ return false; } } public void write() throws IOException { String csvFile = "/Users/lsiao/Desktop/Printer.csv"; FileWriter writer = new FileWriter(csvFile); //(1) CSVUtils.writeLine(writer, new ArrayList<String>(Arrays.asList(String.valueOf(nextId)))); // (2) for (Printer p : inventory) { List<String> list = new ArrayList<>(); // (3) list.add(String.valueOf(p.getId())); list.add(p.getName()); list.add(p.getBrand()); list.add(p.getInkType()); list.add(String.valueOf(p.canWorkWithWifi())); list.add(String.valueOf(p.canPrintDifferentColor())); list.add(String.valueOf(p.canUseForBusiness())); CSVUtils.writeLine(writer, list); // (4) } writer.flush(); writer.close(); } public void loadData(){ String csvFile = "/Users/lsiao/Desktop/Printer.csv"; String line = ""; String csvSplitBy = ","; // (2) try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) { nextId = Integer.parseInt(br.readLine()); // (3) while ((line = br.readLine()) != null) { // split line with comma String[] beer = line.split(csvSplitBy); // (4) int id = Integer.parseInt(beer[0]); String name = beer[1]; String brand = beer[2]; String inkType = beer[3]; boolean wifi = Boolean.parseBoolean(beer[4]); boolean color = Boolean.parseBoolean(beer[5]); boolean bus = Boolean.parseBoolean(beer[6]); // (5) inventory.add(new Printer(id, name, brand, inkType, wifi, color,bus)); System.out.println(id +", " +name+", "+ brand+", " +inkType+", "+ wifi+", "+ color+", "+bus); } } catch (IOException e) { e.printStackTrace(); } } public void jsonWrite() throws IOException { ObjectMapper mapper = new ObjectMapper(); ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter()); writer.writeValue(new File("printer.json"), inventory); } public void jsonLoadData() throws IOException { ObjectMapper objectMapper = new ObjectMapper(); this.inventory = objectMapper.readValue(new File("printer.json"), new TypeReference<ArrayList<Printer>>() { }); System.out.println(objectMapper.writeValueAsString(inventory)); } }
73dba2be034adfd2cf65cd944e0f6ac8c55f73cc
[ "Java" ]
2
Java
jc-hsiao/Product-Inventory-Lab
2e73d86ac6355b9a7f69b153ca6071f9280a3e60
a6f7939df550891154d90bb5741cba98d9ecbc20
refs/heads/master
<repo_name>OlivierRiccini/showcase-api<file_sep>/src/services/organization-service.ts import { Service, Inject } from "typedi"; import { IOrganization, OrganizationDAO } from "../models/organization-model"; import { HttpError } from "routing-controllers"; @Service() export class OrganizationService { @Inject() private organizationDAO: OrganizationDAO; constructor() { } public async createOrganization(organization: IOrganization): Promise<IOrganization> { try { return await this.organizationDAO.create(organization); } catch (err) { throw new HttpError(500, 'Something went wrong while creating new organization'); } } public async updateOrganization(organization: IOrganization, organizationId: string): Promise<IOrganization> { try { return await this.organizationDAO.update(organization, organizationId); } catch (err) { throw new HttpError(500, 'Something went wrong while updating new organization'); } } public async deleteOrganization(organizationId: string): Promise<void> { try { return await this.organizationDAO.delete(organizationId); } catch (err) { throw new HttpError(500, 'Something went wrong while deleting new organization'); } } }<file_sep>/src/controllers/organization-controller.ts const debug = require('debug')('http'); import {JsonController, Body, Put, Param, UseBefore, Delete, Post} from "routing-controllers"; import { Service, Inject } from "typedi"; import { Authenticate } from "../middlewares/auth-middleware"; import { IOrganization } from "../models/organization-model"; import { OrganizationService } from "../services/organization-service"; @JsonController('/organizations') @Service() export class OrganizationController { @Inject() private organizationService: OrganizationService; constructor() { } // @UseBefore(Authenticate) @Post('/') async createOrganization(@Body() organization: IOrganization) { const newOrganization: IOrganization = await this.organizationService.createOrganization(organization); debug('POST /organizations => Successfully created!'); return newOrganization; } // @UseBefore(Authenticate) @Put('/:id') async updateOrganization(@Param('id') id: string , @Body() organization: IOrganization) { const updatedOrganization: IOrganization = await this.organizationService.updateOrganization(organization, id); debug(`PUT /organizations/${id}/update => Successfully updated!`); return updatedOrganization; } // @UseBefore(Authenticate) @Delete('/:id') async deleteOrganization(@Param('id') id: string) { await this.organizationService.deleteOrganization(id); debug(`DEL /organizations/${id} => Successfully deleted!`); return 'Organization successfully deleted!'; } } <file_sep>/src/controllers/catalog-controller.ts import { JsonController, Post, UploadedFile, Get, Param, Res, Delete, UseBefore, HttpError, Req } from 'routing-controllers'; import { Service } from 'typedi'; import { CatalogDAO, ICatalog } from '../models/catalog-model'; import { AdminOnly } from '../middlewares/auth-middleware'; import { Response } from "express"; @JsonController('/catalog') @Service() export class DocumentsController { constructor(private catalogDAO: CatalogDAO) {} // @UseBefore(AdminOnly) @Post() public async uploadsNewDocument(@UploadedFile('file') file: any): Promise<ICatalog> { try { let name = file.originalname; let mimetype = this.catalogDAO.mimetypeOf(file); let buffer = file.buffer; // Regarder si l'extension est valide if (!this.catalogDAO.isSafeFile(name)) { throw new Error('file extension not accepted'); } if (file.path != null) { throw new Error('Unsupported mode of operation for multer - Disk'); } // file.path == null // use buffer let document: ICatalog = { file: buffer, name: name, mimeType: mimetype }; return await this.catalogDAO.create(document); } catch (err) { throw new HttpError(400, err); } } // @UseBefore(AdminOnly) @Get() public async retrievesLastCatalog(@Res() response: Response) { response.set({'Content-Type': 'application/pdf'}); return this.catalogDAO.get().then(data => { return response.status(201).send(Buffer.from(data.file.buffer)); // response.set('Content-Type', data.mimeType); // response.end(data.file.buffer, 'UTF-8'); }) .catch(err => { return response.status(400).send(err); }) } @UseBefore(AdminOnly) @Delete('/:id') deletesDocumentByItsId(@Param('id') id: string, @Res() response: any) { return this.catalogDAO .remove(id) .then(() => { response.status(204); }) .catch(error => { // TODO let global error handler take care of this response.status(500).send(error.message); // return Status.failure(error.message); }); } } <file_sep>/src/services/auth-service.ts import { Service, Inject } from "typedi"; import { UserDAO, IUserCredentials, IForgotPassword, IUser, IPhone } from '../models/user-model'; import { HttpError } from "routing-controllers"; import { SecureService } from "./secure-service"; import validator from 'validator'; import { MailService } from "./mail-service"; import { CONSTANTS } from "../persist/constants"; @Service() export class AuthService { @Inject(type => SecureService) private secureService: SecureService; @Inject() private userDAO: UserDAO; @Inject() private mailService: MailService; constructor() { } public async register(req: any): Promise<any> { try { let user = req; user.password = await this.secureService.hashPassword(user.password); // await this.validateOrganizationId(user); if (user.email) { await this.emailValidation(user.email) }; if (user.phone) { await this.phoneValidation(user.phone) }; user = await this.userDAO.create(req); const tokens = await this.secureService.generateAuthTokens(user); return tokens; } catch (err) { throw new HttpError(400, err.message); } }; public async login(credentials: IUserCredentials): Promise<any> { try { this.validateCredentials(credentials); const query = this.buildQueryFromCredentials(credentials); let users = await this.userDAO.find(query); if (!users || users.length <= 0) { throw new Error('User was not found while login'); } let user = users[0]; await this.secureService.comparePassword(credentials.password, user.password); const tokens = await this.secureService.generateAuthTokens(user); return tokens; } catch (err) { throw new HttpError(400, err.message); } }; public async refreshTokens(refreshToken: string, userId: string) { try { const user: IUser= await this.userDAO.get(userId); await this.secureService.validateRefreshToken(refreshToken); const tokens = await this.secureService.generateAuthTokens(user); return tokens; } catch (err) { throw new HttpError(401, err.message); } } public async forgotPassword(contact: IForgotPassword) { let user: IUser, newPassword: string; try { user = await this.findUserByEmailOrPhone(contact.email, contact.phone); newPassword = await this.secureService.generateNewPassword(); await this.secureService.updatePassword(newPassword, user.id); await this.sendMessagesAfterForgotPassword(contact, newPassword); } catch (err) { throw new HttpError(400, err.message); } } public async isEmailAlreadyTaken(email: string, userId?: string): Promise<boolean> { const users: IUser[] = await this.userDAO.find({find: { email }}); return users.length > 0 && !users.some(user => user.id === userId); } public async isPhoneAlreadyTaken(phone: IPhone, userId?: string): Promise<boolean> { const users: IUser[] = await this.userDAO.find({ find: { 'phone.internationalNumber': phone.internationalNumber } }); return users.length > 0 && !users.some(user => user.id === userId); } public async emailValidation(email: string, userId?: string): Promise<void> { if (await this.isEmailAlreadyTaken(email, userId || null)) { throw new Error('Email address already belongs to an account'); } if (!validator.isEmail(email)) { throw new Error('Email address provided is not valid'); } } public async phoneValidation(phone: IPhone, userId?: string): Promise<void> { if (await this.isPhoneAlreadyTaken(phone, userId || null)) { throw new Error('Phone number already belongs to an account'); } if (!this.isPhoneFormatValid(phone)) { throw new Error('Phone number provided is not valid'); } } public buildQueryFromCredentials(credentials: IUserCredentials): { find: {} } { let query: { find: {} }; if (credentials.email) { query = { find: { email: credentials.email } }; } if (credentials.phone) { query = { find: { 'phone.countryCode': credentials.phone.countryCode, // MORE FLEXIBLE $or: [ {'phone.number': credentials.phone.internationalNumber}, {'phone.internationalNumber': credentials.phone.internationalNumber}, {'phone.nationalNumber': credentials.phone.nationalNumber} ] // 'phone.number': credentials.phone.number, // 'phone.internationalNumber': credentials.phone.internationalNumber, // 'phone.nationalNumber': credentials.phone.nationalNumber, } } } return query; } // private async validateOrganizationId(user: IUser): Promise<void> { // if (!user.organizationId) { // throw new Error('Cannot register user with no organizationId'); // }; // try { // const organization: IOrganization = await this.organizationDAO.get(user.organizationId); // if (!organization) { // throw new Error('Organization id provided is not valid'); // } // } catch (err) { // throw new Error('Organization id provided is not valid'); // } // } private async findUserByEmailOrPhone(email: string, phone: IPhone): Promise<IUser> { const query = email ? { email} : { phone }; const users = await this.userDAO.find({find: query}); if (!users || users.length < 1 || users.length > 1) { throw new HttpError(400, 'No user or more than one user found during password reinitilization process') } return users[0]; } private validateCredentials(credentials: IUserCredentials): void { if (!this.credentialsHaveEmail(credentials) && !this.credentialsHavePhone(credentials)) { throw new Error('User credentials should at least contain an email or a phone property'); } if (this.credentialsHaveEmail(credentials) && !validator.isEmail(credentials.email)) { throw new Error('Provided email is not valid'); } if (this.credentialsHavePhone(credentials) && !this.isPhoneFormatValid(credentials.phone)) { throw new Error('Provided phone number is not valid'); } } private credentialsHaveEmail(credentials: IUserCredentials): boolean { return credentials.hasOwnProperty('email') && !!credentials.email; } private credentialsHavePhone(credentials: IUserCredentials): boolean { return credentials.hasOwnProperty('phone'); } private isPhoneFormatValid(phone: IPhone): boolean { const allPropertiesPresent: boolean = phone.hasOwnProperty('number') && phone.hasOwnProperty('internationalNumber') && phone.hasOwnProperty('nationalNumber') && phone.hasOwnProperty('countryCode'); if (!allPropertiesPresent) { return false; } const formatedPhoneNumber: string = phone.internationalNumber.replace(/\s|\-|\(|\)/gm, ''); return validator.isMobilePhone(formatedPhoneNumber, 'any', {strictMode: true}); } private async sendMessagesAfterForgotPassword(contact: IForgotPassword, newPassword: string): Promise<void> { let user: IUser; switch(contact.type) { case 'email': user = await this.findUserByEmailOrPhone(contact.email, null); await this.mailService.send({ from: '<EMAIL>', to: contact.email, subject: 'New Password', html: ` <p>Bonjour ${user.username.toUpperCase()}, Voici votre nouveau mot de passe: <strong>${newPassword}</strong></p> <p>Pour le modifier:</p> <p>- allez sur la page d'authentification</p> <p>- utilisez votre adresse email et le mots de pass que nous venons de vous envoyer</p> <p>- Changer votre mot de passe</p> <a href="${CONSTANTS.BASE_SPA_URL}/pharmacies/auth">M'authentifier</a> ` }); break; case 'sms': // user = await this.findUserByEmailOrPhone(null, contact.phone); // await this.mailService.sendSMS({ // phone: contact.phone.internationalNumber, // content: `Hey ${user.username.toUpperCase()}, // this is your new password: ${newPassword}. // You can go to your profile to change it` // }); break; default: throw new Error('Something went wrong while reinitilizing password'); } } }<file_sep>/src/models/organization-model.ts import * as mongoose from 'mongoose'; import { ObjectID } from 'bson'; import { DAOImpl } from '../persist/dao'; import { IPhone } from './user-model'; // import validator from 'validator'; // import { ContactMode } from './shared-interfaces'; // const debug = require('debug')('DAO'); delete mongoose.connection.models['Organization']; //Interface for model export interface IOrganization { id?: string, _id?: ObjectID, name: string, email: string, phones: IPhone[], address: string, description?: string } // Document export interface OrganizationDocument extends IOrganization, mongoose.Document { id: string, _id: ObjectID } export class OrganizationDAO extends DAOImpl<IOrganization, OrganizationDocument> { constructor() { const PhoneSchema = new mongoose.Schema({ countryCode: String, internationalNumber: String, nationalNumber: String, number: String, }, { _id : false }); const OrganizationSchema = new mongoose.Schema({ name: String, email: String, phones: [PhoneSchema], address: String, description: String }); super('Organization', OrganizationSchema); } }<file_sep>/src/persist/constants.ts export const CONSTANTS = { ACCESS_TOKEN_SECRET: process.env.ACCESS_TOKEN_SECRET, REFRESH_TOKEN_SECRET: process.env.REFRESH_TOKEN_SECRET, ACCESS_TOKEN_EXPIRES_IN: process.env.ACCESS_TOKEN_EXPIRES_IN, REFRESH_TOKEN_EXPIRES_IN: process.env.REFRESH_TOKEN_EXPIRES_IN, SMTP_AUTH_PASS: process.env.SMTP_AUTH_PASS, BASE_SPA_URL: process.env.BASE_SPA_URL };<file_sep>/src/services/catalog-service.ts import { Service, Inject } from "typedi"; import { HttpError } from "routing-controllers"; // import { CatalogDAO, ICatalog } from "../models/catalog-model"; @Service() export class CatalogService { // @Inject() private catalogDAO: CatalogDAO; // constructor() { } // public async getById(id: string): Promise<ICatalog> { // try { // return await this.catalogDAO.get(id); // } catch (err) { // throw new HttpError(500, 'Something went wrong while getting catalog'); // } // } // public async createCatalog(catalog: ICatalog): Promise<ICatalog> { // try { // return await this.catalogDAO.create(catalog); // } catch (err) { // throw new HttpError(500, 'Something went wrong while creating new catalog'); // } // } // public async updateCatalog(catalog: ICatalog, catalogId: string): Promise<ICatalog> { // try { // return await this.catalogDAO.update(catalog, catalogId); // } catch (err) { // throw new HttpError(500, 'Something went wrong while updating new catalog'); // } // } // public async deleteCatalog(catalogId: string): Promise<void> { // try { // return await this.catalogDAO.delete(catalogId); // } catch (err) { // throw new HttpError(500, 'Something went wrong while deleting new catalog'); // } // } }<file_sep>/test/data-test/common-data.ts import { UserDAO } from '../../src/models/user-model'; import { OrganizationDAO } from '../../src/models/organization-model'; import { ObjectID } from 'bson'; import { CatalogDAO, ICatalog } from '../../src/models/catalog-model'; export const MODELS = [ { name: 'User', DAO: new UserDAO(), }, { name: 'Organization', DAO: new OrganizationDAO(), }, { name: 'Catalog', DAO: new CatalogDAO(), } ]; export const MODELS_DATA = { Organization: [ { _id: new ObjectID('333333333333333333333333'), name: 'Mega Company', email: '<EMAIL>', phones: [{ countryCode: "US", internationalNumber: "+1 234-243-3434", nationalNumber: "(234) 243-3434", number: "+12342433434" }], address: '123 Main Street', description: 'Mega company de la mort qui tue' } ], User: [ { _id: new ObjectID('111111111111111111111111'), username: "<NAME>", email: "<EMAIL>", phone: { countryCode: "US", internationalNumber: "+1 234-243-5654", nationalNumber: "(234) 243-5654", number: "+12342435654" }, organizationId: '333333333333333333333333', password: "<PASSWORD>" }, { _id: new ObjectID('222222222222222222222222'), username: "<NAME>", email: "<EMAIL>", phone: { countryCode: "US", internationalNumber: "+1 234-243-0000", nationalNumber: "(234) 243-0000", number: "+12342430000" }, organizationId: '333333333333333333333333', password: "<PASSWORD>" } ], // Catalog: [ // { // createdOn: new Date(), // lastUpdate: new Date(), // categories: [ // { // name: 'Equipement du domicile', // subCategories: [ // { // name: 'Lit et accessoires', // comments: [ // 'Lit médical', // `La prise en charge est assurée pour les patients ayant // perdu leur autonomie motrice. // Cette perte d&#39;autonomie peut-être transitoire ou // définitive.` // ], // products: [ // { // designation: 'Forfait location lit + potence+ Barrières', // description: `Lit médical standard ou ultra bas (hauteur 19 cm - pour patient Alzheimer)`, // duration: 'semaine', // ratePro: 9.13, // tva: 20, // baseLPPTTC: 12.6, // LPPCode: 1241763 // }, // { // designation: 'Forfait location lit+potence+barrières', // description: 'Lit médical pour enfant de 3à 12 ans', // duration: 'semaine', // ratePro: 17, // tva: 20, // baseLPPTTC: 25, // LPPCode: 1283879 // } // ] // } // ] // } // ] // } // ] }; <file_sep>/src/app.ts const debug = require('debug')('server'); import "reflect-metadata"; // this shim is required import {createExpressServer, useContainer} from "routing-controllers"; import { MongooseConnection } from './db/mongoose-connection'; import { Container } from "typedi"; const envFile = process.env.NODE_ENV ? `./config/${process.env.NODE_ENV}.env` : '.env'; require('dotenv').config({ path: envFile }); useContainer(Container); const PORT = process.env.PORT || 3000; const app = createExpressServer({ cors: true, controllers: [__dirname + "/controllers/**/*.js"], middlewares: [__dirname + "/middlewares/**/*.js"] }); const mongooseConnection = new MongooseConnection(); mongooseConnection.init(); app.set('port', PORT); process.on('uncaughtException', (err) => console.log('uncaughtException= ', err)); app.listen(app.get('port'), () => { debug(`Server running on port ${PORT}`); }); module.exports.app = app; <file_sep>/src/services/user-service.ts import { Service, Inject } from "typedi"; import { IUser, UserDAO } from "../models/user-model"; import { AuthService } from "./auth-service"; import { HttpError } from "routing-controllers"; import { SecureService } from "./secure-service"; import { MailService } from "./mail-service"; import { CONSTANTS } from "../persist/constants"; @Service() export class UserService { @Inject() private secureService: SecureService; @Inject() private userDAO: UserDAO; @Inject() private authService: AuthService; @Inject() private mailService: MailService; constructor() { } public async updateUser(user: IUser, userId: string): Promise<IUser> { try { await this.authService.emailValidation(user.email, userId); return await this.userDAO.update(user, userId); } catch (err) { throw new HttpError(400, err.message); } } public async handleChangePassword(userId: string, oldPassword: string, newPassword: string): Promise<any> { try { const user: IUser = await this.userDAO.get(userId); if (!user) { throw new Error('Change password request rejected since user was not found during process') }; await this.secureService.comparePassword(oldPassword, user.password); await this.secureService.updatePassword(newPassword, userId); if (process.env.NODE_ENV !== 'test') { await this.sendMessagesAfterRestePassword(user, newPassword) }; } catch (err) { throw new HttpError(400, err.message); } }; public async getAll(): Promise<IUser[]> { try { const users = await this.userDAO.getAll(); if (!users) { throw new Error('Something went wrong while retrieving all users'); } return users; } catch(err) { throw new HttpError(404, err.message); } } public async generateNewUser(user: IUser): Promise<IUser> { try { const generatedPassword = await this.secureService.generateNewPassword(); user.password = await this.secureService.hashPassword(generatedPassword); user = await this.userDAO.create(user); await this.mailService.send({ to: user.email, subject: 'Bienvenue chez Balagne Medical Service', html: ` <p>Bonjour ${user.username.toUpperCase()}, nous venons de vous donner accès à notre site internet.</p> <p>Vous pouvez maintenant vous connecter à votre espace avec les identifiants suivants:</p> <span>Adresse email: </span><strong>${user.email}</strong> <br> <span>Mot de passe: </span><strong>${generatedPassword}</strong> <br> <p>Vous pouvez vous y rendre immediatement en cliquant sur lien suivant:</p> <a href="${CONSTANTS.BASE_SPA_URL}/pharmacies/auth">M'authentifier</a> <br> <p>Une fois connecté, vous pourrez modifier votre mot de passe et vos informations</p> <p>Si vous avez des questions, n'hésitez pas à nous contacter</p> <p>Merci et à bientôt chez Balagne Medical Service</p> ` }); return user; } catch(err) { throw new HttpError(404, err.message); } } public async delete(userId: string): Promise<void> { try { return await this.userDAO.delete(userId); } catch(err) { throw new HttpError(404, err.message); } } private async sendMessagesAfterRestePassword(user: IUser, newPassword: string): Promise<void> { if (user.email) { await this.mailService.send({ to: user.email, subject: 'Nouveau mot de passe', html: ` <p>Bonjour ${user.username.toUpperCase()}, vous venez de changer votre mot de passe.</p> <span>Nouveau mot de passe: </span><strong>${newPassword}</strong> <br> <a href="${CONSTANTS.BASE_SPA_URL}/pharmacies/auth">M'authentifier</a> ` }); } } }<file_sep>/src/db/mongoose-connection.ts import mongoose = require('mongoose'); import * as retry from 'retry'; const debug = require('debug')('data-base'); export class MongooseConnection { private mongoDBUri: string; public init() { let i = 1; this.mongoDBUri = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/showcase-api-dev'; mongoose.Promise = global.Promise; const operation = retry.operation({retries: 50}); operation.attempt(() => { mongoose.connect(this.mongoDBUri, { useNewUrlParser: true, socketTimeoutMS: 60000, keepAlive: true, connectTimeoutMS: 60000 }) .then(() => debug(`Successfully connected DB: ${this.mongoDBUri}`)) .catch((err) => { debug(err); debug('Reconnection nb = ' + i++ + ' ...'); if (operation.retry(err)) { return; } }); }); } } <file_sep>/test/http/catalog.test.ts // // 'use strict'; // // var app = require('../../dist/app').app; // // import 'mocha'; // // import * as chai from 'chai'; // // import chaiHttp = require('chai-http'); // // import * as chaiAsPromised from 'chai-as-promised'; // // import { IUser, UserDAO, IUserCredentials } from '../../src/models/user-model'; // // import * as helpers from '../data-test/helpers-data'; // // // import { SecureService } from '../../src/services/secure-service'; // // // import { assert } from 'chai'; // // // import { OrganizationDAO } from '../../src/models/organization-model'; // // import { MODELS_DATA } from '../data-test/common-data'; // // import { ICatalog, ICategory, ISubCategory, IProduct } from '../../src/models/catalog-model'; // // const generalHelper: helpers.GeneralHelper = new helpers.GeneralHelper(); // // const userDAO: UserDAO = new UserDAO(); // // const userHelper: helpers.UserHelper = new helpers.UserHelper(userDAO); // // // const secureService: SecureService = new SecureService(); // // // const organizationDAO: OrganizationDAO = new OrganizationDAO(); // // // const organizationHelper: helpers.organizationHelper = new helpers.organizationHelper(organizationDAO); // // const expect = chai.expect; // // chai.use(chaiHttp); // // chai.use(chaiAsPromised) // // chai.should(); // // describe.only('HTTP - TESTING CATALOG ROUTES ./http/catalog.test', function() { // // const request = chai.request(app).keepOpen(); // // let NON_ADMIN_USER; // // let CATALOG: ICatalog; // // let ADMIN_USER; // // before('Create catalog', async () => { // // generalHelper.cleanDB(); // // NON_ADMIN_USER = await userHelper.getUserAndToken(); // // ADMIN_USER = await userHelper.getAdminUserAndToken(); // // const response = await request // // .post('/catalog') // // .set('Authorization', ADMIN_USER.token) // // .send(MODELS_DATA.Catalog[0]); // // CATALOG = response.body; // // }); // // after('Cleaning DB', async () => { // // generalHelper.cleanDB(); // // // app.close(); // // }); // // it('POSITIVE - Should get catalog if user is auth', async () => { // // const response = await request // // .get('/catalog/' + CATALOG.id) // // .set('Authorization', NON_ADMIN_USER.token); // // expect(response.status).to.equal(200); // // expect(response.body).to.have.property('id'); // // expect(response.body).to.have.property('createdOn'); // // expect(response.body).to.have.property('lastUpdate'); // // expect(response.body).to.have.property('categories'); // // }); // // it('NEGATIVE - Should not get catalog if user is not auth', async () => { // // const response = await request // // .get('/catalog/' + CATALOG.id) // // // .set('Authorization', AUTH_USER.token) // NO TOKEN PROVIDED // // expect(response.status).to.equal(401); // // expect(response.body.message).to.equals('No authorization token provided'); // // }); // // it('POSITIVE - Should add category to catalog if user is admin', async () => { // // const originNbOfCategories = CATALOG.categories.length; // // const newCategory: ICategory = { // // name: 'New category', // // subCategories: [{ // // name: 'Lit et accessoires', // // products: [ // // { // // designation: 'New category Product', // // description: 'New category blabla', // // duration: 'semaine', // // ratePro: 17, // // tva: 20, // // baseLPPTTC: 25, // // LPPCode: 1283879 // // } // // ] // // }] // // }; // // CATALOG.categories.push(newCategory); // // const response = await request // // .put('/catalog/' + CATALOG.id) // // .set('Authorization', ADMIN_USER.token) // // .send(CATALOG); // // const response2 = await request // // .get('/catalog/' + CATALOG.id) // // .set('Authorization', ADMIN_USER.token); // // CATALOG = response2.body; // // expect(response.status).to.equal(200); // // expect(CATALOG.categories.length).to.equal(originNbOfCategories + 1); // // }); // // it('NEGATIVE - Should not add category to catalog if user is not admin', async () => { // // const originNbOfCategories = CATALOG.categories.length; // // const newCategory: ICategory = { // // name: 'New category', // // subCategories: [{ // // name: 'Lit et accessoires', // // products: [ // // { // // designation: 'New category Product', // // description: 'New category blabla', // // duration: 'semaine', // // ratePro: 17, // // tva: 20, // // baseLPPTTC: 25, // // LPPCode: 1283879 // // } // // ] // // }] // // }; // // CATALOG.categories.push(newCategory); // // const response = await request // // .put('/catalog/' + CATALOG.id) // // .set('Authorization', NON_ADMIN_USER.token) // // .send(CATALOG); // // const response2 = await request // // .get('/catalog/' + CATALOG.id) // // .set('Authorization', NON_ADMIN_USER.token); // // CATALOG = response2.body; // // expect(response.status).to.equal(401); // // expect(response.body.message).to.equals('Only admin can perform this action'); // // expect(CATALOG.categories.length).to.equal(originNbOfCategories); // // }); // // it('POSITIVE - Should add sub-category to catalog if user is admin', async () => { // // const originNbOfSubCategories = CATALOG.categories[0].subCategories.length; // // const newSubCategory: ISubCategory = { // // name: 'Lit et accessoires', // // products: [ // // { // // designation: 'New category Product', // // description: 'New category blabla', // // duration: 'semaine', // // ratePro: 17, // // tva: 20, // // baseLPPTTC: 25, // // LPPCode: 1283879 // // } // // ] // // }; // // CATALOG.categories[0].subCategories.push(newSubCategory); // // const response = await request // // .put('/catalog/' + CATALOG.id) // // .set('Authorization', ADMIN_USER.token) // // .send(CATALOG); // // const response2 = await request // // .get('/catalog/' + CATALOG.id) // // .set('Authorization', ADMIN_USER.token); // // CATALOG = response2.body; // // expect(response.status).to.equal(200); // // expect(CATALOG.categories[0].subCategories.length).to.equal(originNbOfSubCategories + 1); // // }); // // it('NEGATIVE - Should not add sub-category to catalog if user is not admin', async () => { // // const originNbOfSubCategories = CATALOG.categories[0].subCategories.length; // // const newSubCategory: ISubCategory = { // // name: 'Lit et accessoires', // // products: [ // // { // // designation: 'New category Product', // // description: 'New category blabla', // // duration: 'semaine', // // ratePro: 17, // // tva: 20, // // baseLPPTTC: 25, // // LPPCode: 1283879 // // } // // ] // // }; // // CATALOG.categories[0].subCategories.push(newSubCategory); // // const response = await request // // .put('/catalog/' + CATALOG.id) // // .set('Authorization', NON_ADMIN_USER.token) // // .send(CATALOG); // // const response2 = await request // // .get('/catalog/' + CATALOG.id) // // .set('Authorization', NON_ADMIN_USER.token); // // CATALOG = response2.body; // // expect(response.status).to.equal(401); // // expect(response.body.message).to.equals('Only admin can perform this action'); // // expect(CATALOG.categories[0].subCategories.length).to.equal(originNbOfSubCategories); // // }); // // it('POSITIVE - Should update product if user is admin', async () => { // // const product: IProduct = CATALOG.categories[0].subCategories[0].products[0]; // // product.LPPCode = 11111; // // const response = await request // // .put('/catalog/' + CATALOG.id) // // .set('Authorization', ADMIN_USER.token) // // .send(CATALOG); // // const response2 = await request // // .get('/catalog/' + CATALOG.id) // // .set('Authorization', ADMIN_USER.token); // // CATALOG = response2.body; // // const updatedProduct = CATALOG.categories[0].subCategories[0].products[0]; // // expect(response.status).to.equal(200); // // expect(updatedProduct.LPPCode).to.equal(11111); // // }); // // // it('POSITIVE - Should add product to catalog if user is admin', async () => { // // // }); // // it('NEGATIVE - Should not update product if user is not admin', async () => { // // const product: IProduct = CATALOG.categories[0].subCategories[0].products[0]; // // const originLPPCode = product.LPPCode; // // product.LPPCode = 11111; // // const response = await request // // .put('/catalog/' + CATALOG.id) // // .set('Authorization', NON_ADMIN_USER.token) // // .send(CATALOG); // // const response2 = await request // // .get('/catalog/' + CATALOG.id) // // .set('Authorization', NON_ADMIN_USER.token); // // CATALOG = response2.body; // // const nonUpdatedProduct = CATALOG.categories[0].subCategories[0].products[0]; // // expect(response.status).to.equal(401); // // expect(nonUpdatedProduct.LPPCode).to.equal(originLPPCode); // // }); // // // //// // // // it('POSITIVE - Should update category to catalog if user is admin', async () => { // // // }); // // // it('NEGATIVE - Should not update category to catalog if user is not admin', async () => { // // // }); // // // it('POSITIVE - Should update sub-category to catalog if user is admin', async () => { // // // }); // // // it('NEGATIVE - Should not update sub-category to catalog if user is not admin', async () => { // // // }); // // // it('POSITIVE - Should update product to catalog if user is admin', async () => { // // // }); // // // it('NEGATIVE - Should not update product to catalog if user is not admin', async () => { // // // }); // // // //// // // // it('POSITIVE - Should delete category to catalog if user is admin', async () => { // // // }); // // // it('NEGATIVE - Should not delete category to catalog if user is not admin', async () => { // // // }); // // // it('POSITIVE - Should delete sub-category to catalog if user is admin', async () => { // // // }); // // // it('NEGATIVE - Should not delete sub-category to catalog if user is not admin', async () => { // // // }); // // // it('POSITIVE - Should delete product to catalog if user is admin', async () => { // // // }); // // // it('NEGATIVE - Should not delete product to catalog if user is not admin', async () => { // // // }); // // }); // 'use strict'; // var app = require('../../dist/app').app; // import 'mocha'; // import * as helpers from '../data-test/helpers-data'; // let path = require('path'); // // let fs = require('fs'); // import * as chaiAsPromised from 'chai-as-promised'; // import chai = require('chai'); // import chaiHttp = require('chai-http'); // import { UserDAO } from '../../src/models/user-model'; // chai.use(chaiHttp); // chai.should(); // // import 'mocha'; // // import * as chai from 'chai'; // // import chaiHttp = require('chai-http'); // // import * as chaiAsPromised from 'chai-as-promised'; // // import { IUser, UserDAO, IUserCredentials } from '../../src/models/user-model'; // // import * as helpers from '../data-test/helpers-data'; // // // import { SecureService } from '../../src/services/secure-service'; // // // import { assert } from 'chai'; // // // import { OrganizationDAO } from '../../src/models/organization-model'; // // import { MODELS_DATA } from '../data-test/common-data'; // // import { ICatalog, ICategory, ISubCategory, IProduct } from '../../src/models/catalog-model'; // const generalHelper: helpers.GeneralHelper = new helpers.GeneralHelper(); // const userDAO: UserDAO = new UserDAO(); // const userHelper: helpers.UserHelper = new helpers.UserHelper(userDAO); // describe.only("E2E /documents API", () => { // const request = chai.request(app).keepOpen(); // let smallFilename = path.basename(__filename) + ".pdf"; // let largeFilename = 'large_file.pdf'; // let ext = path.extname(smallFilename); // const mongoMaxLength = 16777216; // 16 777 216 ~ 16 MB // let largeBuffer = Buffer.alloc(mongoMaxLength + 100, "bonjour."); // let NON_ADMIN_USER; // let ADMIN_USER; // before('Create catalog', async () => { // generalHelper.cleanDB(); // NON_ADMIN_USER = await userHelper.getUserAndToken(); // ADMIN_USER = await userHelper.getAdminUserAndToken(); // }); // after('Cleaning DB', async () => { // generalHelper.cleanDB(); // // app.close(); // }); // it("C54 C56 C60 Positive POST /documents as admin", async () => { // let response = await request // .post('/catalog') // .set('Authorization', ADMIN_USER) // .attach("file", __filename, smallFilename); // console.log(response.body); // response.should.be.ok; // response.should.be.json; // response.body.should.have.property('id'); // response.body.should.have.property('name'); // response.body.name.should.be.equals(smallFilename); // const id = response.body.id; // path.extname(id).should.be.equals(ext); // response = await request // .get('/documents/' + id); // response.should.be.ok; // response = await request // .del('/documents' + id) // .set('Authorization', ADMIN_USER) // response.should.be.ok; // response.status.should.be.equal(204); // return response; // }); // it('C57 Negative POST /documents as anonymous', async () => { // try { // await request // .post('/catalog/') // .attach("file", __filename, smallFilename) // } // catch (error) { // const response = error.response // response.status.should.be.equals(401); // } // }); // it('C57 Negative POST /documents if no admin', async () => { // try { // await request // .post('/catalog/') // .set('Authorization', NON_ADMIN_USER) // .attach("file", __filename, smallFilename) // } // catch (error) { // const response = error.response // response.status.should.be.equals(401); // } // }); // it('C55 should upload large document', async function () { // // large file to upload, give it more time // let response = await request // .post("/catalog/") // .set('Authorization', ADMIN_USER) // .attach("file", largeBuffer, largeFilename) // response.should.be.ok; // response.should.be.json; // response.body.should.have.property('id'); // response.body.should.have.property('name'); // response.body.name.should.be.equals(largeFilename); // const id = response.body.id; // path.extname(id).should.be.equals(path.extname(largeFilename)); // response = await request.get("/documents/" + id) // response.should.be.ok; // response = await request // .del("/documents/" + id) // .set('Authorization', ADMIN_USER) // response.should.be.ok; // response.status.should.be.equal(204); // }); // it.skip("C61 +Positive - Effacer un document non-existant", async () => { // const id = '000000000000'; // try { // const response = await request // .del("/catalog/" + id) // .set('Authorization', ADMIN_USER) // response.should.not.be.ok; // } catch (error) { // error.status.should.be.equals(500); // } // }); // }); <file_sep>/test/http/organization.test.ts 'use strict'; var app = require('../../dist/app').app; import 'mocha'; import * as chai from 'chai'; import chaiHttp = require('chai-http'); import * as chaiAsPromised from 'chai-as-promised'; import { IUser, UserDAO, IUserCredentials } from '../../src/models/user-model'; import * as helpers from '../data-test/helpers-data'; import { SecureService } from '../../src/services/secure-service'; import { assert } from 'chai'; import { OrganizationDAO } from '../../src/models/organization-model'; const generalHelper: helpers.GeneralHelper = new helpers.GeneralHelper(); const userDAO: UserDAO = new UserDAO(); const userHelper: helpers.UserHelper = new helpers.UserHelper(userDAO); const secureService: SecureService = new SecureService(); const organizationDAO: OrganizationDAO = new OrganizationDAO(); const organizationHelper: helpers.organizationHelper = new helpers.organizationHelper(organizationDAO); const expect = chai.expect; chai.use(chaiHttp); chai.use(chaiAsPromised) chai.should(); describe('HTTP - TESTING ORGANIZATION ROUTES ./http/organization.test', function() { const request = chai.request(app).keepOpen(); // let VALID_USER: IUser = { // username: 'Lebron', // email: '<EMAIL>', // password: '<PASSWORD>', // phone: { // countryCode: "US", // internationalNumber: "+1 438-399-1332", // nationalNumber: "(438) 399-1332", // number: "+14383991332" // }, // organizationId: '333333333333333333333333' // }; // const VALID_USER_CREDENTIALS_EMAIL: IUserCredentials = { // email: '<EMAIL>', // password: 'IamTheKing' // }; // let VALID_USER_TOKEN: string; before('Create user', async () => { generalHelper.cleanDB(); // await organizationHelper.create(); // const response = await request // .post('/auth/register') // .send(VALID_USER); // let token = response.body['jwt']; // VALID_USER.id = userHelper.getIdByToken(token); // VALID_USER_TOKEN = token; }); after('Cleaning DB', async () => { generalHelper.cleanDB(); // app.close(); }); }); <file_sep>/test/data-test/helpers-data.ts const debug = require('debug')('seed'); import { UserDAO, IUser } from '../../src/models/user-model'; import * as chai from 'chai'; import chaiHttp = require('chai-http'); import { MODELS_DATA } from './common-data'; import * as jwt from 'jsonwebtoken'; import { CONSTANTS } from '../../src/persist/constants'; import { OrganizationDAO, IOrganization } from '../../src/models/organization-model'; import { ObjectID } from 'bson'; // import { SecureService } from '../../src/services/secure-service'; var mongoose = require('mongoose'); chai.use(chaiHttp); var app = require('../../dist/app').app; export class GeneralHelper { constructor() {} public cleanDB(): void { const db = mongoose.connection; db.dropDatabase(); } } export class organizationHelper { constructor(private organizationDAO: OrganizationDAO) {} public async create(): Promise<IOrganization> { return this.organizationDAO.create(MODELS_DATA.Organization[0]); } } export class UserHelper { private request = chai.request(app).keepOpen(); constructor(private userDAO: UserDAO) { } public async getUserById(userId: string | number): Promise<any> { return this.userDAO.get(userId); } public async getUserAndToken(user?: IUser): Promise<{ user: IUser, token: string }> { const newUser = user ? user : MODELS_DATA.User[0]; const response = await this.request .post('/auth/register') .send(newUser) let token = response.body['jwt']; if (token.startsWith('Bearer ')) { // Remove Bearer from string token = token.slice(7, token.length); } const decoded = jwt.verify(token, CONSTANTS.ACCESS_TOKEN_SECRET, null); const userResponse = decoded['payload']; return { user: userResponse, token }; } public async getAdminUserAndToken(): Promise<{ user: IUser, token: string }> { const user: IUser = { _id: new ObjectID('111111111111111111111110'), username: "Big Boss", email: "<EMAIL>", phone: { countryCode: "US", internationalNumber: "+1 234-243-2222", nationalNumber: "(234) 243-2222", number: "+12342432222" }, organizationId: '<PASSWORD>', password: "<PASSWORD>", isAdmin: true }; const response = await this.request .post('/auth/register') .send(user) let token = response.body['jwt']; if (token.startsWith('Bearer ')) { // Remove Bearer from string token = token.slice(7, token.length); } const decoded = jwt.verify(token, CONSTANTS.ACCESS_TOKEN_SECRET, null); const userResponse = decoded['payload']; return { user: userResponse, token }; } public async deleteAllUsers(): Promise<any> { return this.userDAO.deleteAll(); } public async delete(userId: string | number): Promise<any> { return this.userDAO.delete(userId); } public getIdByToken(token: string): string { if (token.startsWith('Bearer ')) { // Remove Bearer from string token = token.slice(7, token.length); } const decoded = jwt.verify(token, CONSTANTS.ACCESS_TOKEN_SECRET, null); const user = decoded['payload']; return user.id; } } <file_sep>/src/services/mail-service.ts import nodemailer = require('nodemailer'); import { Service } from 'typedi'; import { IEmail } from '../models/email-model'; import { CONSTANTS } from '../persist/constants'; const debug = require('debug')('app'); @Service() export class MailService { public async send(email: IEmail): Promise<any> { // debug('Sending email via', this.config.host + ':' + this.config.port); const transport = this.getConfiguredTransport(); const mail = this.buildMail(email); return new Promise((resolve, reject) => { transport.sendMail(mail, (error, info) => { if (error) { console.error('Error sending email', error); reject(error); } else { debug('Successfully sent email', JSON.stringify(info)); resolve(info); } }); }); } private buildMail(email: IEmail): any { const mail = { from: `<EMAIL>`, sender: email.from, to: email.to, subject: email.subject, html: email.html }; return mail; } private getConfiguredTransport(): any { return nodemailer.createTransport({ host: 'smtp-mail.outlook.com', // hostname secure: false, // TLS requires secureConnection to be false port: 587, // port for secure SMTP tls: { ciphers:'SSLv3' }, auth: { user: '<EMAIL>', pass: CONSTANTS.SMTP_AUTH_PASS } }) } }<file_sep>/src/controllers/message-controller.ts const debug = require('debug')('http'); import {JsonController, Body, Post, HttpError} from "routing-controllers"; import { Service, Inject } from "typedi"; import { MailService } from "../services/mail-service"; import { IEmail } from "../models/email-model"; // import { MessagesService } from "../services/messages-service"; // import { IEmail, ISMS } from "../messaging/message-interfaces"; @JsonController('/messages') @Service() export class MessageController { @Inject() private mailService: MailService; constructor() { } @Post('/email') async sendEmail(@Body() email: IEmail): Promise<string> { try { await this.mailService.send(email); debug('POST /message/email => Email successfully sent!'); return 'Email successfully sent!'; } catch(err) { debug(err.message) throw new HttpError(err); } } @Post('/test') async testMessage(@Body() message: { to: string; text: string }): Promise<string> { try { debug('POST /messages/test => Test message sent!'); return `Test message working. You sent ${message.text} to ${message.to}`; } catch(err) { debug(err.message) } } } <file_sep>/src/models/catalog-model.ts import * as _ from 'lodash'; import * as mongoose from 'mongoose'; import { ObjectID } from 'bson'; import { DAOImpl } from '../persist/dao'; let mimetypes = require('mime-types'); let path = require('path'); let stream = require('stream'); const MemoryStream = require('memory-stream'); delete mongoose.connection.models['Catalog']; export interface ICatalog { id?: string; name: string; file?: Buffer; mimeType?: string; } // Document interface Catalog extends ICatalog, mongoose.Document { id: string, _id: ObjectID } // // Document export interface CatalogDocument extends ICatalog, mongoose.Document { id: string, _id: ObjectID } export class CatalogDAO extends DAOImpl<ICatalog, CatalogDocument> { private result; constructor() { const CatalogSchema = new mongoose.Schema({ name: String, file: Buffer, mimeType: String }); super('Catalog', CatalogSchema); } // CatalogModel: any = null; public mimetypeOf(file: any) { let mimetype = file.mimeType ? file.mimetype : mimetypes.lookup(file.originalname); if (!mimetype) { mimetype = 'application/octet-stream'; } return mimetype; } public isSafeFile(filename: string): boolean { let ext = path.extname(filename).toLowerCase(); var re = new RegExp('bmp|dib|dng|doc|docx|dwg|gif|jpg|pdf|png|ppt|pptx|rtf|tif|txt|vsd|xls|xlsx|xml'); let matches = ext.match(re); if (matches) { return true; } return false; } private stripExtension(id: string) { if (id.indexOf('.') > -1) { id = id.substr(0, id.lastIndexOf('.')); } return id; } private makeReadStream(obj: ICatalog) { // Initiate the source var bufferStream = new stream.PassThrough(); // Write your buffer bufferStream.end(obj.file); return bufferStream; } private makeWritableStream() { return new MemoryStream(); } public create(obj: ICatalog): Promise<ICatalog> { return new Promise<any>((resolve, reject) => { // let metadata = Object.assign({}, obj); const options: any = { metadata: { contentType: obj.mimeType } }; const bucket = new mongoose.mongo.GridFSBucket(mongoose.connection.db); // Drop DB to keep just one catalog stored in it bucket.drop(); this.makeReadStream(obj) .pipe(bucket.openUploadStream(obj.name, options)) .on('error', (error) => { reject(error); }) .on('finish', (uploadedFileInfo) => { const ext = path.extname(uploadedFileInfo.filename); const result = { id: uploadedFileInfo._id.toString() + ext, name: uploadedFileInfo.filename, mimeType: obj.mimeType }; resolve(result); }); }); } public async get(): Promise<ICatalog> { return new Promise<any>((resolve, reject) => { const bucket = new mongoose.mongo.GridFSBucket(mongoose.connection.db); bucket .find() .sort({ _id: -1 }) .limit(1) .toArray() .then((items: any[]) => { if (items.length > 0) { const item = items[0]; const memstream = this.makeWritableStream(); const oid = mongoose.Types.ObjectId(this.stripExtension(item._id.toString())); bucket .openDownloadStream(oid) .pipe(memstream) .on('error', (error) => { reject(error); }) .on('finish', () => { let ext = path.extname(item.filename); let result = { id: item._id.toString() + ext, mimeType: item.metadata.contentType, file: { buffer: memstream.toBuffer() }, name: item.filename }; resolve(result); }); } }) .catch((error) => reject(error)); }); } public getByid(id: string): Promise<ICatalog> { return new Promise<any>((resolve, reject) => { let bucket = new mongoose.mongo.GridFSBucket(mongoose.connection.db); let oid = mongoose.Types.ObjectId(this.stripExtension(id)); let filters = { _id: oid }; bucket .find(filters) .toArray() .then((items: any[]) => { if (items.length > 0) { let item = items[0]; let memstream = this.makeWritableStream(); bucket .openDownloadStream(oid) .pipe(memstream) .on('error', function(error) { reject(error); }) .on('finish', function() { let ext = path.extname(item.filename); let result = { id: item._id.toString() + ext, mimeType: item.metadata.contentType, file: { buffer: memstream.toBuffer() }, name: item.filename }; resolve(result); }); } else { reject('Document not found'); } }); }); } public remove(id: string): Promise<any> { return new Promise<any>((resolve, reject) => { let bucket = new mongoose.mongo.GridFSBucket(mongoose.connection.db); let oid = mongoose.Types.ObjectId(this.stripExtension(id)); bucket.delete(oid, error => { if (error) reject(error); resolve(true); }); }); } }<file_sep>/src/middlewares/auth-middleware.ts import { ExpressMiddlewareInterface, HttpError } from "routing-controllers"; import * as jwt from 'jsonwebtoken'; import { Service } from "typedi"; import { CONSTANTS } from '../persist/constants' @Service() export class Authenticate implements ExpressMiddlewareInterface { private _adminOnly: boolean; constructor(adminOnly) { this._adminOnly = adminOnly; } use(request: any, response: any, next: (err?: any) => Promise<any>) { let accessToken = request.header('Authorization'); try { if (!accessToken) { throw new HttpError(401, 'No authorization token provided'); } if (accessToken.startsWith('Bearer ')) { // Remove Bearer from string accessToken = accessToken.slice(7, accessToken.length); } const decoded = jwt.verify(accessToken, CONSTANTS.ACCESS_TOKEN_SECRET, null); if (typeof decoded === 'undefined') { throw new HttpError(401, 'Authorizationt token cannot be decoded'); }; const user = decoded['payload']; if (!user) { throw new HttpError(401, 'This token is not related to any user'); }; if (this._adminOnly && !user.isAdmin) { throw new HttpError(401, 'Only admin can perform this action'); } request.user = user; request.token = accessToken; next(); } catch(err) { response.status(err.httpCode ? err.httpCode : 401).send(err) } } } export class AdminOnly extends Authenticate { constructor() { super(true); } }
71c360d84a824169c0616929e124a436b2155cf6
[ "TypeScript" ]
18
TypeScript
OlivierRiccini/showcase-api
b920790912c83ae316afc022f1a3718451954b2b
704594acac7b207a95d5f8ac35e469f8e53266ce
refs/heads/master
<file_sep>package com.android.project.firechat.activities; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Patterns; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Toast; import com.android.project.firechat.R; import com.android.project.firechat.shared.SharedPrefManager; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthUserCollisionException; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.HashMap; public class RegisterActivity extends AppCompatActivity { private static final String TAG = "RegisterActivity"; //layout private Button backBtn, registerBtn; private EditText userNameText,emailText, passwordText; private FirebaseAuth mAuth; private ProgressBar progressBar; //firebase private DatabaseReference firebaseDatabase; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); userNameText = findViewById(R.id.userNameText); emailText = findViewById(R.id.emailText); passwordText = findViewById(R.id.passwordText); backBtn = findViewById(R.id.backBtn); registerBtn = findViewById(R.id.searchBtn); progressBar = findViewById(R.id.progressBar); mAuth = FirebaseAuth.getInstance(); backBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(RegisterActivity.this, MainActivity.class)); } }); registerBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { registerUser(); } }); } public void registerUser(){ final String email = emailText.getText().toString().trim(); final String password = passwordText.getText().toString().trim(); final String userName = userNameText.getText().toString().trim(); //validation if (userName.isEmpty() || userName.length() > 10){ userNameText.setError("Username is required"); userNameText.requestFocus(); return; } if (email.isEmpty()){ emailText.setError("Email is required!"); emailText.requestFocus(); return; } if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()){ emailText.setError("Please enter a valid email"); } if (password.isEmpty()){ passwordText.setError("Password is required!"); passwordText.requestFocus(); return; } if (password.length() < 6){ passwordText.setError("Minimum password length is 6"); passwordText.requestFocus(); return; } progressBar.setVisibility(View.VISIBLE); mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { progressBar.setVisibility(View.GONE); if (task.isSuccessful()){ Toast.makeText(getApplicationContext(), "User register successful", Toast.LENGTH_SHORT).show(); FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser(); String uid = currentUser.getUid(); //getReference points at root directory in db firebaseDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(uid); //save user to database HashMap<String, String> userMap = new HashMap<>(); userMap.put("name", userName); userMap.put("status", "Firechat is da bomb yo!"); userMap.put("image", "default"); userMap.put("thumbImage", "default"); userMap.put("Contacts", ""); firebaseDatabase.setValue(userMap); // Saves token for notifications FirebaseDatabase.getInstance().getReference().child("Tokens").child(uid) .setValue(SharedPrefManager.getInstance(getApplicationContext()).getToken()); //start new activity Intent intent = new Intent(RegisterActivity.this, UserActivity.class); //clear all open activities and open new one //this is to make sure that the back button cant be used passed UserActivity intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); }else { //Email is already registered if (task.getException() instanceof FirebaseAuthUserCollisionException){ Toast.makeText(getApplicationContext(), "This email is already registered", Toast.LENGTH_SHORT).show(); }else{ //else try to get message that caused the error try{ Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show(); }catch (NullPointerException ex){ Toast.makeText(getApplicationContext(), "Some error has occurred, please try again", Toast.LENGTH_SHORT).show(); } } } } }); } } <file_sep>package com.android.project.firechat.activities; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.telecom.Call; import android.util.Log; import android.util.Patterns; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.android.project.firechat.R; import com.android.project.firechat.shared.SharedPrefManager; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.login.LoginManager; import com.facebook.login.LoginResult; import com.facebook.login.widget.LoginButton; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.FirebaseDatabase; import com.facebook.FacebookSdk; import com.facebook.appevents.AppEventsLogger; import java.util.Arrays; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; //layout private Button loginBtn; private EditText emailText, passwordText; private ProgressBar progressBar; //private LoginButton loginButton; CallbackManager callbackManager; private TextView registerAcc; //firebase private FirebaseAuth mAuth; @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { callbackManager.onActivityResult(requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FacebookSdk.sdkInitialize(getApplicationContext()); setContentView(R.layout.activity_main); AppEventsLogger.activateApp(this); callbackManager = CallbackManager.Factory.create(); final String EMAIL = "email"; emailText = findViewById(R.id.emailText); passwordText = findViewById(R.id.passwordText); loginBtn = findViewById(R.id.loginBtn); progressBar = findViewById(R.id.progressBar); registerAcc = findViewById(R.id.textViewRegister); //loginButton = (LoginButton) findViewById(R.id.login_button); // loginButton.setReadPermissions(Arrays.asList(EMAIL)); // If you are using in a fragment, call loginButton.setFragment(this); mAuth = FirebaseAuth.getInstance(); /* // Callback registration loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { // App code startActivity(new Intent(MainActivity.this, UserActivity.class)); } @Override public void onCancel() { // App code } @Override public void onError(FacebookException exception) { // App code } }); */ /* LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { startActivity(new Intent(MainActivity.this, UserActivity.class)); } @Override public void onCancel() { } @Override public void onError(FacebookException error) { } }); */ loginBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { userLogin(); } }); registerAcc.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.d(TAG, "onCreate: Register button pressed"); startActivity(new Intent(MainActivity.this, RegisterActivity.class)); } }); } public void userLogin(){ Log.d(TAG, "userLogin: Login button pressed, validating info"); String email = emailText.getText().toString().trim(); String password = passwordText.getText().toString().trim(); //validation if (email.isEmpty()){ emailText.setError("Email is required!"); emailText.requestFocus(); return; } if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()){ emailText.setError("Please enter a valid emailText"); } if (password.isEmpty()){ passwordText.setError("Password is required!"); passwordText.requestFocus(); return; } if (password.length() < 6){ passwordText.setError("Minimum passwordText length is 6"); passwordText.requestFocus(); return; } progressBar.setVisibility(View.VISIBLE); mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { progressBar.setVisibility(View.GONE); if (task.isSuccessful()){ Log.d(TAG, "userLogin: login successful"); // Saves token for notifications FirebaseDatabase.getInstance().getReference().child("Tokens") .child(FirebaseAuth.getInstance().getUid()) .setValue(SharedPrefManager.getInstance(getApplicationContext()).getToken()); //start new activity Intent intent = new Intent(MainActivity.this, UserActivity.class); //clear all open activities and open new one //this is to make sure that the back button cant be used passed UserActivity intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); }else { try{ Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show(); }catch (NullPointerException ex){ Toast.makeText(getApplicationContext(), "Some error has occurred, please try again", Toast.LENGTH_SHORT).show(); } } } }); } } <file_sep>package com.android.project.firechat; import java.util.HashMap; import java.util.Map; public class ChatMessageItem { private String message; private String timestamp; private String senderName; private String senderUid; private String receiverUid; public ChatMessageItem() { // Default constructor required for calls to DataSnapshot.getValue(ChatMessageItem.class) } public ChatMessageItem(String message, String timestamp, String username, String senderUid, String receiverUid) { this.message = message; this.timestamp = timestamp; this.senderName = username; this.senderUid = senderUid; this.receiverUid = receiverUid; } public String getMessage() { return message; } public String getTimestamp() { return timestamp; } public String getSenderName() { return senderName; } public String getSenderUid() { return this.senderUid; } public HashMap<String, String> toMap() { HashMap<String, String> result = new HashMap<>(); result.put("message", this.message); result.put("timestamp", this.timestamp); result.put("senderName", this.senderName); result.put("senderUid", this.senderUid); result.put("receiverUid", this.receiverUid); return result; } } <file_sep>package com.android.project.firechat.fragments; import android.support.v4.app.Fragment; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Intent; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Set; import com.android.project.firechat.R; public class Tab3XXX extends Fragment{ private BluetoothAdapter BA; private Set<BluetoothDevice>pairedDevices; private ArrayAdapter<String> discoveredDevicesAdapter; TextView statusText; ListView listView; Button deviceSearchBtn,makeVisibleBtn,turnOnOff; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.tab3xxx, container, false); listView = rootView.findViewById(R.id.listView2); deviceSearchBtn = rootView.findViewById(R.id.devices_search); makeVisibleBtn = rootView.findViewById(R.id.visibleBtn); statusText = rootView.findViewById(R.id.status); turnOnOff = rootView.findViewById(R.id.onOffBtn); BA = BluetoothAdapter.getDefaultAdapter(); turnOnOff.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (BA.isEnabled()){ BA.disable(); }else{ Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(turnOn, 0); } } }); makeVisibleBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { makeVisible(); } }); deviceSearchBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getDevices(); } }); return rootView; } public void getDevices(){ pairedDevices = BA.getBondedDevices(); ArrayList list = new ArrayList(); for(BluetoothDevice bt : pairedDevices) list.add(bt.getName()); Toast.makeText(getActivity().getApplicationContext(), "Showing Paired Devices",Toast.LENGTH_SHORT).show(); final ArrayAdapter adapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1, list); listView.setAdapter(adapter); } public void makeVisible(){ Intent getVisible = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); startActivityForResult(getVisible, 0); } } <file_sep>package com.android.project.firechat.activities; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.android.project.firechat.R; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.ArrayList; import java.util.HashMap; class SearchViewAdapter extends ArrayAdapter<Contact>{ //refers to the contact that is clicked in listview //private Contact contact; //layout private TextView userNameTextView, userStatusTextView; private Button addBtn; private ImageView profileImage; //firebase private DatabaseReference firebaseDatabase; private FirebaseUser currentUser; SearchViewAdapter(Context context, ArrayList<Contact> users){ super(context, R.layout.contact_row, users); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { LayoutInflater layoutInflater = LayoutInflater.from(getContext()); View customRow = layoutInflater.inflate(R.layout.contact_row, parent, false); userNameTextView = (TextView) customRow.findViewById(R.id.userNameText); userStatusTextView = (TextView) customRow.findViewById(R.id.userStatusText); addBtn = (Button) customRow.findViewById(R.id.removeBtn); profileImage = (ImageView) customRow.findViewById(R.id.userProfileImage); //get contact that is clicked final Contact contact = getItem(position); addBtn.setText(R.string.add); userNameTextView.setText(contact.getUserName()); userStatusTextView.setText(contact.getStatus()); addBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //add contact to database currentUser = FirebaseAuth.getInstance().getCurrentUser(); String uid = currentUser.getUid(); //getReference points at root directory in db firebaseDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(uid).child("Contacts").child(contact.getUserId()); //save user to database HashMap<String, Object> userMap = new HashMap<>(); userMap.put("username", contact.getUserName()); firebaseDatabase.updateChildren(userMap); Toast.makeText(getContext(), contact.getUserName() + " added to contacts", Toast.LENGTH_SHORT).show(); } }); return customRow; } } <file_sep>package com.android.project.firechat.fragments; import android.content.Intent; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import com.android.project.firechat.R; import com.android.project.firechat.activities.Contact; import com.android.project.firechat.activities.ContactListAdapter; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; public class Tab1Contact extends Fragment { //layout private ListView contactListView; private ArrayList<Contact> contactList = new ArrayList<>(); private ContactListAdapter adapter; //firebase DatabaseReference firebaseDatabase; @Override public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { adapter = new ContactListAdapter(getActivity(), contactList); if (!contactList.isEmpty()){ contactList.clear(); adapter.clear(); } View rootView = inflater.inflate(R.layout.tab1contacts, container, false); contactListView = rootView.findViewById(R.id.contactListView); contactListView.setAdapter(adapter); FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser(); String uid = currentUser.getUid(); firebaseDatabase = FirebaseDatabase.getInstance().getReference("Users").child(uid).child("Contacts"); firebaseDatabase.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (!contactList.isEmpty()){ contactList.clear(); adapter.clear(); } //add contacts for (final DataSnapshot snapshot : dataSnapshot.getChildren()){ Contact contact = new Contact(snapshot.child("username").getValue().toString(), snapshot.getKey()); contactList.add(contact); } //add status to contact (not the best solution but works) for (final Contact c : contactList){ firebaseDatabase = FirebaseDatabase.getInstance().getReference("Users").child(c.getUserId()).child("status"); firebaseDatabase.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { c.setStatus(dataSnapshot.getValue().toString()); adapter.notifyDataSetChanged(); } @Override public void onCancelled(DatabaseError databaseError) { } }); } } @Override public void onCancelled(DatabaseError databaseError) { } }); return rootView; } } <file_sep># Firechat ## Project information ``` IDE: Android Studio Programming language: Java ``` ## Description ``` A realtime chat application developed for Android smartphones on the Google Firebase platform. The development group included four students and was developed during the course Mobile Applications at Högskolan Kristianstad. ``` ## Learning outcomes ``` *Google Firebase platform *Realtime database *Facebook SDK *Google Maps *Bluetooth communication with Android devices *Agile workflow ``` # Login & Profile settings <img src="images/firechat_login.png">&emsp;<img src="images/firechat_profilesettings.PNG"> # Contacts & Chat <img src="images/firechat_contacts.PNG">&emsp;<img src="images/firechat_chat.PNG"> <file_sep>package com.android.project.firechat.activities; import com.android.project.firechat.R; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import java.util.ArrayList; public class SearchContactsActivity extends AppCompatActivity { //layout private ArrayList<Contact> resultList = new ArrayList<>(); private String searchResult; private ListView searchResultView; private EditText userNameText,emailText; private ProgressBar progressBar; private Button searchBtn; //firebase private DatabaseReference firebaseDatabase; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search_contacts); userNameText = findViewById(R.id.userNameText); emailText = findViewById(R.id.emailText); searchBtn = findViewById(R.id.searchBtn); searchResultView = findViewById(R.id.searchResultView); final SearchViewAdapter adapter = new SearchViewAdapter(this, resultList); searchBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (!resultList.isEmpty()){ resultList.clear(); adapter.clear(); } firebaseDatabase = FirebaseDatabase.getInstance().getReference("Users"); firebaseDatabase.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot snapshot : dataSnapshot.getChildren()){ String userName = snapshot.child("name").getValue().toString(); String userId = snapshot.getKey(); String userStatus = snapshot.child("status").getValue().toString(); Contact contact = new Contact(userName, userId, userStatus); if (userName.contains(userNameText.getText().toString())){ resultList.add(contact); } } searchResultView.setAdapter(adapter); } @Override public void onCancelled(DatabaseError databaseError) { } }); } }); } }
87067bac50f06cd16230af4001a87ac6baa7078b
[ "Markdown", "Java" ]
8
Java
martinbacs/Firechat
a556d99b6042acf3bef73ab7f47ad4acd56e70c2
55f86d036f4528860e28be7d9e1bf5b29aa77cb1
refs/heads/master
<repo_name>RallyTechServices/rally-feature-board<file_sep>/App.js Ext.define('CustomApp', { extend: 'Rally.app.App', componentCls: 'app', logger: new Rally.technicalservices.logger(), launch: function() { var me = this; this.cardboard = Ext.create('Rally.ui.cardboard.CardBoard',{ types: ['PortfolioItem/Feature'], attribute: 'Release', columnConfig: { xtype: 'rallycardboardcolumn', displayField: 'Name', valueField: '_ref', plugins: [ {ptype:'rallycolumndropcontroller'}, {ptype:'rallycardboardcardrecordprocessor'}, {ptype:'tscolumnheaderupdater'} /*, {ptype:'tscolumnheaderupdater', field_to_aggregate: 'LeafStoryPlanEstimateTotal'}*/ ] }, storeConfig:{ }, cardConfig: { showIconsAndHighlightBorder: false, fields: [ 'FormattedID', 'Name', { name: 'Project', renderer: me._renderProject }, 'State', { name: 'PercentDoneByStoryPlanEstimate' }, { name: 'c_FeatureEstimate', fetch: ['c_FeatureEstimate'] } ], listeners: { added: function(card,container){ me.logger.log(this,card,container); }, fieldClick: function(eOpts) { me.logger.log(this,eOpts); if ( eOpts == "PercentDoneByStoryPlanEstimate" ) { me._showDoneTooltip(eOpts,this); } } } } }); this.add(this.cardboard); }, _showDoneTooltip:function(field_name,card) { var me = this; var record = card.getRecord(); var progress = card.getEl().down('.progress-bar-container'); me.logger.log("record", record.data); Ext.create('Rally.ui.popover.PercentDonePopover', { target: progress, percentDoneData: record.data, percentDoneName: field_name, piRef: record.data._ref }); }, _renderProject: function(value) { return value.get('Name'); } }); <file_sep>/ts-plugin-card-releasealignment.js Ext.define('Rally.ui.cardboard.plugin.ReleaseAlignment', { extend: 'Ext.AbstractPlugin', alias: 'plugin.tscardreleasealignment', init: function(cmp) { this.callParent(arguments); this._addField(); }, _addAlignmentClickListener: function() { var element_id = this.cmp.record.get('FormattedID') + '-releasealignment'; var marker = Ext.query('#'+element_id); if ( marker.length > 0 ){ Ext.get(marker[0]).on('click',this._showPopover,this); } }, _showPopover: function() { var me = this; var count = this.cmp.record.get('UnalignedStories'); if ( count > 0 ) { if ( this.popover ) { this.popover.destroy(); } this.popover = Ext.create('Rally.ui.popover.Popover',{ target: me.cmp.getEl(), items: [ me._getPopoverContents() ] }); this.popover.show(); } }, _releaseGridRenderer: function(value) { if ( value && typeof( value ) == "object" ) { return value._refObjectName; } else { return value; } }, _storyLinkRenderer: function(value,meta,record) { return Rally.nav.DetailLink.getLink({ showHover: false, record:record.getData(), text:record.get("FormattedID") }); }, _getPopoverContents: function() { var me = this; var record = this.cmp.record; var store = Ext.create('Rally.data.WsapiDataStore',{ model:'UserStory', filters: [ {property:'Feature.ObjectID', value: record.get('ObjectID') }, {property:'DirectChildrenCount',value:0 } ], context: null, autoLoad: true, pageSize: 5 }); var grid = Ext.create('Rally.ui.grid.Grid',{ store: store, columnCfgs: [ {text:'id',dataIndex:'FormattedID',renderer: me._storyLinkRenderer}, {text:'Name',dataIndex:'Name'}, {text:'Size',dataIndex:'PlanEstimate'}, {text:'Release',dataIndex:'Release',renderer: me._releaseGridRenderer,editor:'rallyreleasecombobox'}, {text:'State',dataIndex:'ScheduleState'} ], pagingToolbarCfg: { pageSizes: [5, 10, 25] } }); return grid; }, _addField: function() { var me = this; var record = this.cmp.getRecord(); var cmp = this.cmp; cmp.addField({ name: "Release", renderTpl: function() { me._findAlignment(); return [ '<div id="' + record.get('FormattedID') + '-releasealignment">', '', '</div>' ].join(''); }, isStatus: false }); }, //TODO: stop calling it a feature _findAlignment: function() { var me = this; var feature = this.cmp.getRecord(); var release = feature.get('Release'); var feature_fid = feature.get('FormattedID'); if ( release ) { var filters = [ {property:'Feature.FormattedID',value: feature_fid}, {property:'Release.Name',operator:'!=',value:release.Name}, {property:'DirectChildrenCount',value:0} ]; Ext.create('Rally.data.WsapiDataStore',{ autoLoad: true, model:'UserStory', filters:filters, listeners: { load: function(store,records,operation) { var html = ""; var out_of_sync_total = 0; if ( records.length > 0 ) { html = "# User Stories Not in Release: <span class='status-warn'>" + records.length + "</span>"; } Ext.query('#' + feature_fid + '-releasealignment')[0].innerHTML = html; Ext.Array.each( records, function(record) { var estimate = record.get('PlanEstimate') || 0; out_of_sync_total += parseFloat(estimate,10); }); me.cmp.record.set('UnalignedStories',records.length); me.cmp.record.set('UnalignedStoriesPlanEstimateTotal',out_of_sync_total); me.cmp.fireEvent('datachanged', me.cmp, records, operation); me._addAlignmentClickListener(); } } }); } return true; } });<file_sep>/README.md rally-feature-board =================== A planning board by feature/release
79a2e53c2b5876f0630d34fce302906174a81878
[ "JavaScript", "Markdown" ]
3
JavaScript
RallyTechServices/rally-feature-board
70b1949a93ba9f8caf5546bcab0bebb9317d6f47
cf70bb2f7cd6f2533002984ef87e3668c876f4b0
refs/heads/master
<file_sep>var express = require('express'); var router = express.Router(); var productController = require("./controller/productController") router.get('/', function (req, res, next) { res.send('respond with a resource'); }); router.get('/get-all-products', function (req, res, next) { productController.getAllProducts(function (err, payload) { if (err) { res.status(500).json({ message: "error", error: err }) } else { res.json({ message: "success", data: payload }) } }) }); router.get('/get-product-by-id/:id',function (req, res, next) { productController.getProductByID(req.params.id,function (err, payload) { if (err) { res.status(500).json({ message: "error", error: err }) } else { res.json({ message: "success", data: payload }) } }) }); router.post("/create-product", function (req, res) { productController.createProduct(req.body, function (err, payload) { if (err) { res.status(500).json({ message: "Error", error: err }); } else { res.json({ message: "success", data: payload }); } }); }); router.put('/update-product-by-id/:id', function (req, res) { productController.updateProductByID(req.params.id,req.body, function (err, payload) { if (err) { res.status(500).json({ message: "Error", error: err }); } else { res.json({ message: "success", data: payload }); } }); }); router.delete("/delete-product-by-id/:id", function (req, res) { productController.deleteProductByID(req.params.id, function (err, deletedPayload) { if (err) { res.status(500).json({ message: "Error", error: err }); } else { res.json({ message: "success", data: deletedPayload }); } }); }); module.exports = router;
b95fbb015ee4d314a289888021971dd5423e252c
[ "JavaScript" ]
1
JavaScript
minahil435/homework-practice-mongodb
70f21964f5478fb15ea0f3c74f12a14bc5b5ac73
4a6cf4e732771133b0f499c4307c698cda105915
refs/heads/master
<repo_name>oxenprogrammer/Mimopay-Android-SDK<file_sep>/SampleApp/src/com/bayninestudios/texturemodeldemo/MainActivity.java package com.bayninestudios.texturemodeldemo; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.opengl.GLSurfaceView; import android.opengl.GLU; import android.opengl.GLUtils; import android.os.Bundle; import android.view.MotionEvent; import android.os.Handler; import android.os.Build; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; //import android.app.Activity; //import android.content.Context; import android.content.pm.ActivityInfo; //import android.opengl.GLSurfaceView; //import android.opengl.GLU; //import android.os.Bundle; import android.util.Log; import android.content.Intent; import android.view.Menu; import android.view.MenuItem; import android.view.Window; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.view.ViewGroup.LayoutParams; import android.widget.EditText; import android.widget.TextView; import android.widget.Button; import android.widget.ImageButton; import android.widget.CheckBox; import android.graphics.Typeface; import android.view.View.OnClickListener; import android.view.View; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.StateListDrawable; import android.widget.Toast; import android.app.Dialog; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.view.LayoutInflater; import android.view.ViewGroup; import android.view.View.OnTouchListener; // java import java.util.ArrayList; // mimopay import com.mimopay.Mimopay; import com.mimopay.MimopayInterface; import com.mimopay.merchant.Merchant; import javax.crypto.Cipher; public class MainActivity extends Activity { public void jprintf(String s) { Log.d("JimBas", "MainActivity: " + s); } private GLSurfaceView mGLView; private final int TOPUP = 1; private final int SMARTFREN = 2; private final int SEVELIN = 3; private final int ATM = 4; private final int BCA = 5; private final int BERSAMA = 6; private final int UPOINT = 7; private final int XL = 8; private final int XLAIRTIME = 9; private final int XLHRN = 10; private final int MPOINT = 11; private final int DPOINT = 12; private final int LASTRESULT = 13; private final int STAGGATE = 14; private final int holobluelight = 0xff33b5e5; private final int holobluedark = 0xff0099cc; private final int holobluebright = 0xff00ddff; private final int TOTALMENUBTNS = 14; private ImageButton mbtnPay = null; private View[] mbtnMenuBtns = null; private int[] mnMenuBtns = { R.id.shoplistbtntopup, R.id.shoplistbtntopupsmartfren, R.id.shoplistbtntopupsevelin, R.id.shoplistbtnupoint, R.id.shoplistbtnatm, R.id.shoplistbtnatmbca, R.id.shoplistbtnatmbersama, R.id.shoplistbtnxl, R.id.shoplistbtnxlairtime, R.id.shoplistbtnxlvoucher, R.id.shoplistbtnmpointairtime, R.id.shoplistbtndpointairtime, R.id.shoplistbtnlastresult, R.id.shoplistbtnstaggate }; private int[] mnMenuBtnsInitId = { TOPUP, SMARTFREN, SEVELIN, UPOINT, ATM, BCA, BERSAMA, XL, XLAIRTIME, XLHRN, MPOINT, DPOINT, LASTRESULT, STAGGATE }; private View mvShop = null; private boolean mbShopBtn = false; private boolean mbGateway = false; // Called when the activity is first created. @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Thread.setDefaultUncaughtExceptionHandler(new TopExceptionHandler()); //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); LayoutInflater inflater = getLayoutInflater(); mvShop = getLayoutInflater().inflate(R.layout.shop, null); mbtnPay = (ImageButton) mvShop.findViewById(R.id.shoplistbtnpay); mbtnPay.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if(mBtnShopHandler != null) return true; mbShopBtn = !mbShopBtn; v.setPressed(mbShopBtn); View vv = (View) mvShop.findViewById(R.id.shoplistitems); if(vv != null) { vv.setVisibility(mbShopBtn ? View.VISIBLE : View.GONE); if(mbShopBtn) { Handler handler = new Handler(); handler.postDelayed(new Runnable(){@Override public void run() { LinearLayout llshop = (LinearLayout) mvShop.findViewById(R.id.shoplayout); llshop.getLayoutParams().width = mbtnPay.getLayoutParams().width; }}, 1000); } } mBtnShopHandler = new Handler(); mBtnShopHandler.postDelayed(mBtnShopRunnable, 500); return true; }}); mGLView = new ClearGLSurfaceView(this); setContentView(mGLView); mbtnMenuBtns = new View[TOTALMENUBTNS]; for(int i=0;i<TOTALMENUBTNS;i++) { mbtnMenuBtns[i] = mvShop.findViewById(mnMenuBtns[i]); final int fi = i; mbtnMenuBtns[i].setOnClickListener(new OnClickListener(){ public void onClick(View view) { if(mBtnChooseHandler != null) return; mnBtnChooseId = fi; mBtnChooseHandler = new Handler(); mBtnChooseHandler.postDelayed(mBtnChooseRunnable, 500); }}); } getWindow().addContentView(mvShop, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); //initMimopay(); } private class TopExceptionHandler implements Thread.UncaughtExceptionHandler { private Thread.UncaughtExceptionHandler defaultUEH; TopExceptionHandler() { this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler(); } public void uncaughtException(Thread t, Throwable e) { jprintf("AbnormalTermination. reason: " + e.toString()); //defaultUEH.uncaughtException(t, e); System.exit(666); } } private Handler mBtnShopHandler = null; Runnable mBtnShopRunnable = new Runnable() { @Override public void run() { mBtnShopHandler = null; }}; private Handler mBtnChooseHandler = null; private int mnBtnChooseId = 0; Runnable mBtnChooseRunnable = new Runnable() { @Override public void run() { runOnUiThread(new Runnable() { public void run() { jprintf("togglebutton: " + Integer.toString(mnBtnChooseId)); mbShopBtn = false; mbtnPay.setPressed(mbShopBtn); View v = (View) mvShop.findViewById(R.id.shoplistitems); if(v != null) { v.setVisibility(View.GONE); } mBtnChooseHandler = null; initMimopay(mnMenuBtnsInitId[mnBtnChooseId]); }}); }}; @Override protected void onPause() { super.onPause(); if(mGLView != null) { mGLView.onPause(); } } @Override protected void onResume() { super.onResume(); if(mGLView != null) { mGLView.onResume(); } } boolean mQuietMode = false; Mimopay mMimopay = null; MimopayInterface mMimopayInterface = new MimopayInterface() { public void onReturn(String info, ArrayList<String> params) { String s,toastmsg = ""; jprintf("onReturn: " + info); if(params != null) { toastmsg += (info + "\n\n"); int i,j = params.size(); for(i=0;i<j;i++) { s = params.get(i); toastmsg += (s + "\n"); jprintf(String.format("[%d] %s", i, s)); } if(mQuietMode) { final String ftoastmsg = toastmsg; runOnUiThread(new Runnable() { public void run() { Toast.makeText(getApplicationContext(), ftoastmsg, Toast.LENGTH_LONG).show(); }}); } } } }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Main codes of How to use Mimopay SDK. // // To have better understanding it is strongly recommend to refer to http://staging.mimopay.com/api documentation. // Before create Mimopay object, you need to fill parameters that is described in documentation. Values that is used // in this sample is our mimopay's internal test account. // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void initMimopay(int paymentid) { String emailOrUserId = "1385479814"; // this parameter is your user's unique id or user's email. Normally your app/game should have unique ID for every user String merchantCode = "ID-0031"; // for this parameter, after registration to mimopay, your should received this from us String productName = "ID-0031-0001"; // this parameter is also your own territory. It will be pass back to your server, either successful or an error occurs String transactionId = ""; // this should be unique in every transaction. If you leave it empty, SDK will generate unique numbers based on unix timestamp String secretKeyStaging = null; String secretKeyGateway = null; // You may initiate secretKeyStaging and secretKeyGateway hard-coded in your app's source code, however if this is not appropriate, you may use our // encrypted secretKey to avoid it. Every registerred merchant should received two files from us, jar file and txt file. Txt file contains secretKey's encrypted-key, // while the jar file contains secretKey's encrypted-value. So all you need to do is select and copy the encrypted-key from txt file, paste into Merchant.get() parameter, // it will return your real secretKey. try { secretKeyStaging = Merchant.get(true, "<KEY>); secretKeyGateway = Merchant.get(false, "<KEY>); } catch(Exception e) { jprintf("e: " + e.toString()); } String currency = "IDR"; if(secretKeyStaging == null || secretKeyGateway == null) { Toast.makeText(getApplicationContext(), "secretKey problem!", Toast.LENGTH_LONG).show(); return; } mMimopay = new Mimopay(getApplicationContext(), emailOrUserId, merchantCode, productName, transactionId, secretKeyStaging, secretKeyGateway, currency, mMimopayInterface); // enableLog is Mimopay SDK's internal log print. If set to enable, all logs will printed out in your app's log. This is very usefull in your development phase mMimopay.enableLog(true); // By default, the payment process will goes to staging.mimopay.com. Keep it commented out while you are still in development phase, // when you are ready to production you can un-comment it, so SDK will goes to gateway.mimopay.com // mMimopay.enableGateway(mbGateway); AlertDialog.Builder altbld = null; AlertDialog alert = null; mQuietMode = false; // As stated in Mobile SDK documentation, it support two modes, UI and Quiet mode. UI mode methods have no // parameter(s) in it while Quiet mode methods have. switch (paymentid) { case TOPUP: // // this will launch UI mode top up activity. One or more payment channels will be shown, may not be the same every merchants // mMimopay.executeTopup(); break; case SMARTFREN: // smartfren altbld = new AlertDialog.Builder(MainActivity.this); altbld.setMessage("Mimopay's SDK supports both, Default UI and Quiet Mode. " + "In Quiet Mode, the voucher number is currently set to 1234567890123456. " + "You may change it later in this sample source code.\n" + "Now, please choose which one.") .setCancelable(true) .setPositiveButton("UI", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // // this will launch UI mode top up activity and straight to show Smartfren channel. // mMimopay.executeTopup("smartfren"); }}) .setNegativeButton("Quiet", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mQuietMode = true; // // Running Smartfren top up quietly (quiet mode). The running background task will straight call for Smartfren channel, // and do the top up with the number that passed in the second parameter. No UI will pops up. // You will notified the result via MimopayInterface.onReturn, check its 'info' string status // mMimopay.executeTopup("smartfren", "9861529055077264"); }}); alert = altbld.create(); alert.setTitle("Smartfren Topup"); alert.setIcon(android.R.drawable.stat_notify_error); alert.show(); break; case SEVELIN: // sevelin altbld = new AlertDialog.Builder(MainActivity.this); altbld.setMessage("Mimopay's SDK supports both, Default UI and Quiet Mode. " + "In Quiet Mode, the voucher number is currently set to 1234567890123456. " + "You may change it later in this sample source code.\n" + "Now, please choose which one.") .setCancelable(true) .setPositiveButton("UI", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // // UI mode for sevelin, straight to show Sevelin channel // mMimopay.executeTopup("sevelin"); }}) .setNegativeButton("Quiet", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mQuietMode = true; // // Running Sevelin top up quietly. You will notified the result via MimopayInterface.onReturn // check its 'info' string status // mMimopay.executeTopup("sevelin", "1234567890123456"); }}); alert = altbld.create(); alert.setTitle("Sevelin Topup"); alert.setIcon(android.R.drawable.stat_notify_error); alert.show(); break; case ATM: // ATM mMimopay.executeATMs(); break; case BCA: // ATM BCA altbld = new AlertDialog.Builder(MainActivity.this); altbld.setMessage("Mimopay's SDK supports both, Default UI and Quiet Mode. " + "In Quiet Mode, the value of mimocard is currently set to 50K. " + "You may change it later in this sample source code.\n" + "Now, please choose which one.") .setCancelable(true) .setPositiveButton("UI", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mMimopay.executeATMs("atm_bca"); }}) .setNegativeButton("Quiet", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mQuietMode = true; mMimopay.executeATMs("atm_bca", "50000"); }}); alert = altbld.create(); alert.setTitle("ATM BCA"); alert.setIcon(android.R.drawable.stat_notify_error); alert.show(); break; case BERSAMA: // ATM Bersama altbld = new AlertDialog.Builder(MainActivity.this); altbld.setMessage("Mimopay's SDK supports both, Default UI and Quiet Mode. " + "In Quiet Mode, the value of mimocard is currently set to 50K. " + "You may change it later in this sample source code.\n" + "Now, please choose which one.") .setCancelable(true) .setPositiveButton("UI", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mMimopay.executeATMs("atm_bersama"); }}) .setNegativeButton("Quiet", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mQuietMode = true; mMimopay.executeATMs("atm_bersama", "50000"); }}); alert = altbld.create(); alert.setTitle("ATM Bersama"); alert.setIcon(android.R.drawable.stat_notify_error); alert.show(); break; case UPOINT: // upoint altbld = new AlertDialog.Builder(MainActivity.this); altbld.setMessage("Mimopay's SDK supports both, Default UI and Quiet Mode. " + "In Quiet Mode, the UPoint credits is currently set to 1000 and phone number is 081219106541. " + "You may change them later in this sample source code.\n" + "Now, please choose which one.") .setCancelable(true) .setPositiveButton("UI", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { //mMimopay.executeUPointAirtime(); AlertDialog.Builder altbld = new AlertDialog.Builder(MainActivity.this); altbld.setMessage("Denom list or fixed denom ?") .setCancelable(true) .setPositiveButton("Denom List", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mMimopay.executeUPointAirtime(); }}) .setNegativeButton("Fixed Denom (1000)", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mMimopay.executeUPointAirtime("1000"); }}); AlertDialog aldlg = altbld.create(); aldlg.setTitle("Language"); aldlg.setIcon(android.R.drawable.stat_notify_error); aldlg.show(); }}) .setNegativeButton("Quiet", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mQuietMode = true; mMimopay.executeUPointAirtime("1000", "081219106541", false); //mMimopay.executeUPointAirtime("25000"); }}); alert = altbld.create(); alert.setTitle("UPoint Airtime"); alert.setIcon(android.R.drawable.stat_notify_error); alert.show(); break; case XL: // XL mMimopay.executeXL(); break; case XLAIRTIME: // XL Airtime altbld = new AlertDialog.Builder(MainActivity.this); altbld.setMessage("Mimopay's SDK supports both, Default UI and Quiet Mode. " + "In Quiet Mode, the XL Airtime credits is currently set to 10000 and phone number is 087771270843. " + "You may change them later in this sample source code.\n" + "Now, please choose which one.") .setCancelable(true) .setPositiveButton("UI", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mMimopay.executeXLAirtime(); }}) .setNegativeButton("Quiet", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mQuietMode = true; mMimopay.executeXLAirtime("10000", "087771270843 ", false); //mMimopay.executeXLAirtime("20000"); //Toast.makeText(getApplicationContext(), "not yet implemented", Toast.LENGTH_LONG).show(); }}); alert = altbld.create(); alert.setTitle("XL Airtime"); alert.setIcon(android.R.drawable.stat_notify_error); alert.show(); break; case XLHRN: // XL HRN altbld = new AlertDialog.Builder(MainActivity.this); altbld.setMessage("Mimopay's SDK supports both, Default UI and Quiet Mode. " + "In Quiet Mode, the voucher number (HRN) is currently set to 1234567890123456. " + "You may change it later in this sample source code.\n" + "Now, please choose which one.") .setCancelable(true) .setPositiveButton("UI", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mMimopay.executeXLHrn(); }}) .setNegativeButton("Quiet", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mQuietMode = true; mMimopay.executeXLHrn("1234567890123456"); }}); alert = altbld.create(); alert.setTitle("XL HRN"); alert.setIcon(android.R.drawable.stat_notify_error); alert.show(); break; case MPOINT: // mpoint altbld = new AlertDialog.Builder(MainActivity.this); altbld.setMessage("Mimopay's SDK supports both, Default UI and Quiet Mode. " + "In Quiet Mode, the MPoint Airtime credits is currently set to 2 and phone number is 0175629621. " + "You may change them later in this sample source code.\n" + "Now, please choose which one.") .setCancelable(true) .setPositiveButton("UI", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { AlertDialog.Builder altbld = new AlertDialog.Builder(MainActivity.this); altbld.setMessage("Choose your language ?\n(Dutch language here just an example)") .setCancelable(true) .setPositiveButton("English", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mMimopay.executeMPointAirtime(); }}) .setNegativeButton("Dutch", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Please note that payment methods those are in Bahasa by default, cannot be customized. // Since MPoint is in English by default, you can do as below if you want to customized to other language. // Please refer to CustomLang.java, it shows how all words should be managed. jprintf(String.format("CustomLang.mDutch:%d", CustomLang.mDutch.length)); mMimopay.setUiLanguage(CustomLang.mDutch); mMimopay.executeMPointAirtime(); }}); AlertDialog aldlg = altbld.create(); aldlg.setTitle("Language"); aldlg.setIcon(android.R.drawable.stat_notify_error); aldlg.show(); }}) .setNegativeButton("Quiet", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mQuietMode = true; mMimopay.executeMPointAirtime("2", "0175629621", false); //Toast.makeText(getApplicationContext(), "Quiet mode disabled for temporary", Toast.LENGTH_LONG).show(); }}); alert = altbld.create(); alert.setTitle("MPoint Airtime"); alert.setIcon(android.R.drawable.stat_notify_error); alert.show(); break; case DPOINT: // dpoint altbld = new AlertDialog.Builder(MainActivity.this); altbld.setMessage("Mimopay's SDK supports both, Default UI and Quiet Mode. " + "In Quiet Mode, the DPoint Airtime credits is currently set to 200 and phone number is 0169041289. " + "You may change them later in this sample source code.\n" + "Now, please choose which one.") .setCancelable(true) .setPositiveButton("UI", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { AlertDialog.Builder altbld = new AlertDialog.Builder(MainActivity.this); altbld.setMessage("Choose your language ?\n(Dutch language here just an example)") .setCancelable(true) .setPositiveButton("English", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mMimopay.executeDPointAirtime(); }}) .setNegativeButton("Dutch", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Please note that payment methods those are in Bahasa by default, cannot be customized. // Since DPoint is in English by default, you can do as below if you want to customized to other language. // Please refer to CustomLang.java, it shows how all words should be managed. mMimopay.setUiLanguage(CustomLang.mDutch); mMimopay.executeDPointAirtime(); }}); AlertDialog aldlg = altbld.create(); aldlg.setTitle("Language"); aldlg.setIcon(android.R.drawable.stat_notify_error); aldlg.show(); }}) .setNegativeButton("Quiet", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { AlertDialog.Builder altbld = new AlertDialog.Builder(MainActivity.this); altbld.setMessage("Choose DPoint Payment ?") .setCancelable(true) .setPositiveButton("New Transaction", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mQuietMode = true; mMimopay.executeDPointAirtime("0", "60169041289", false); }}) .setNegativeButton("Complete Last Payment", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { if(!mMimopay.isDPointPaymentIncomplete()) { Toast.makeText(getApplicationContext(), "The last transaction was not DPoint payment method", Toast.LENGTH_LONG).show(); } else { final Dialog smsdlg = new Dialog(MainActivity.this); smsdlg.requestWindowFeature(Window.FEATURE_NO_TITLE); smsdlg.setContentView(R.layout.digismscode); Button smsdlgButton = (Button) smsdlg.findViewById(R.id.smscodeTopup); smsdlgButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mQuietMode = true; EditText edit = (EditText) smsdlg.findViewById(R.id.smscodeEditText); mMimopay.completeDPointPayment(edit.getText().toString()); smsdlg.dismiss(); }}); smsdlg.show(); } }}); AlertDialog aldlg = altbld.create(); aldlg.setTitle("Language"); aldlg.setIcon(android.R.drawable.stat_notify_error); aldlg.show(); }}); alert = altbld.create(); alert.setTitle("DPoint Airtime"); alert.setIcon(android.R.drawable.stat_notify_error); alert.show(); break; case LASTRESULT: String s = ""; int ires = 0; String [] sarr = mMimopay.getLastResult(); if(sarr != null) { ires = sarr.length; for(int i=0;i<ires;i++) { s += (sarr[i] + "\n"); } } //String toastmsg = String.format("ires=%d\ns=%s", ires, s); Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show(); break; case STAGGATE: mbGateway = !mbGateway; Button btn = (Button) mbtnMenuBtns[STAGGATE-1]; btn.setText(mbGateway ? "Switch to Staging" : "Switch to Gateway"); Toast.makeText(getApplicationContext(), "SDK will points to " + (mbGateway ? "Gateway" : "Staging") + " on next transaction", Toast.LENGTH_LONG).show(); break; } } } class ClearGLSurfaceView extends GLSurfaceView { ClearRenderer mRenderer; private final float TOUCH_SCALE_FACTOR = 180.0f / 320; private final float TRACKBALL_SCALE_FACTOR = 36.0f; private float mPreviousX; private float mPreviousY; private Handler mAfterTouchHandler = null; public ClearGLSurfaceView(Context context) { super(context); mRenderer = new ClearRenderer(context, this); setRenderer(mRenderer); } @Override public boolean onTrackballEvent(MotionEvent e) { afterTouch(); mRenderer.mAngleX += e.getX() * TRACKBALL_SCALE_FACTOR; mRenderer.mAngleY += e.getY() * TRACKBALL_SCALE_FACTOR; requestRender(); return true; } @Override public boolean onTouchEvent(MotionEvent e) { float x = e.getX(); float y = e.getY(); switch (e.getAction()) { case MotionEvent.ACTION_MOVE: afterTouch(); float dx = x - mPreviousX; float dy = y - mPreviousY; mRenderer.mAngleX += dx * TOUCH_SCALE_FACTOR; mRenderer.mAngleY += dy * TOUCH_SCALE_FACTOR; requestRender(); } mPreviousX = x; mPreviousY = y; return true; } private void afterTouch() { mRenderer.autoRotate = false; if(mAfterTouchHandler == null) mAfterTouchHandler = new Handler(); mAfterTouchHandler.postDelayed(mStageRunnable, 1000); } Runnable mStageRunnable = new Runnable() { @Override public void run() { mRenderer.autoRotate = true; mAfterTouchHandler = null; }}; } class ClearRenderer implements GLSurfaceView.Renderer { private ClearGLSurfaceView view; private Context context; private DrawModel model; //private float angleY = 0f; public float mAngleX = 0f; public float mAngleY = 0f; public boolean autoRotate = true; private int[] mTexture = new int[1]; public ClearRenderer(Context context, ClearGLSurfaceView view) { this.view = view; this.context = context; model = new DrawModel(context, R.raw.rock); } private void loadTexture(GL10 gl, Context mContext, int mTex) { gl.glGenTextures(1, mTexture, 0); gl.glBindTexture(GL10.GL_TEXTURE_2D, mTexture[0]); Bitmap bitmap; bitmap = BitmapFactory.decodeResource(mContext.getResources(), mTex); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); bitmap.recycle(); } public void onSurfaceCreated(GL10 gl, EGLConfig config) { gl.glLoadIdentity(); GLU.gluPerspective(gl, 25.0f, (view.getWidth() * 1f) / view.getHeight(), 1, 100); GLU.gluLookAt(gl, 0f, 0f, 12f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glEnable(GL10.GL_DEPTH_TEST); gl.glEnable(GL10.GL_TEXTURE_2D); loadTexture(gl, context, R.drawable.rock); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexEnvx(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_MODULATE); } public void onSurfaceChanged(GL10 gl, int w, int h) { gl.glViewport(0, 0, w, h); } public void onDrawFrame(GL10 gl) { //gl.glClearColor(0f, 0f, .7f, 1.0f); gl.glClearColor(0f, 0f, 0f, 1.0f); gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); gl.glPushMatrix(); //gl.glRotatef(angleY, 0f, 1f, 0f); gl.glRotatef(mAngleX, 0, 1, 0); gl.glRotatef(mAngleY, 1, 0, 0); model.draw(gl); gl.glPopMatrix(); //angleY += 1f; if(autoRotate) mAngleX += 1f; } } <file_sep>/README.md Mimopay-Android-SDK =================== Making Payment Simple and Easy in your Android app Mimopay Android SDK is designed to help you integrate your android application or games to Mimopay’s payment gateway. Mimopay Android SDK equipped with a built-in UI as well as quiet mode operation. Quiet mode means that after you initiate execution, the SDK will do the payment process in background instead of popping up its built-in UI. This will allow you to continue with other process that you want to do. All information, whether an error occurs or a successful payment, will be notified via ‘onReturn’ callback method <file_sep>/SimpleSample/src/com/jandroid/simplesample/MainActivity.java package com.jandroid.simplesample; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; import android.util.Log; import android.view.View; import android.widget.Toast; import android.app.AlertDialog; import android.content.DialogInterface; import android.view.View.OnClickListener; import android.widget.Button; // java import java.util.ArrayList; // mimopay import com.mimopay.Mimopay; import com.mimopay.MimopayInterface; import com.mimopay.merchant.Merchant; public class MainActivity extends Activity { public void dp(String s) { Log.d("JimBas", "SimpleSample: " + s); } private final int TOPUP = 1; private final int SMARTFREN = 2; private final int SEVELIN = 3; private final int ATM = 4; private final int BCA = 5; private final int BERSAMA = 6; private final int UPOINT = 7; private final int XL = 8; private final int XLAIRTIME = 9; private final int XLHRN = 10; private final int MPOINT = 11; private final int LASTRESULT = 12; private final int STAGGATE = 13; private boolean mbGateway = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); dp("MainActivity: onCreate"); setContentView(R.layout.main); } @Override protected void onStart() { super.onStart(); dp("MainActivity: onStart"); } @Override protected void onStop() { super.onStop(); dp("MainActivity: onStop"); } @Override protected void onResume() { super.onResume(); dp("MainActivity: onResume"); } @Override protected void onPause() { super.onPause(); dp("MainActivity: onPause"); } @Override protected void onDestroy() { super.onDestroy(); dp("MainActivity: onDestroyed"); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // TOP UP public void onClickTopup(View view) { initMimopay(TOPUP); } public void onClickSmartfren(View view) { initMimopay(SMARTFREN); } public void onClickSevelin(View view) { initMimopay(SEVELIN); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ATMs public void onClickAtms(View view) { initMimopay(ATM); } public void onClickAtmBca(View view) { initMimopay(BCA); } public void onClickAtmBersama(View view) { initMimopay(BERSAMA); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Upoint public void onClickUpoint(View view) { initMimopay(UPOINT); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // XL public void onClickXl(View view) { initMimopay(XL); } public void onClickXlPulsa(View view) { initMimopay(XLAIRTIME); } public void onClickXlVoucher(View view) { initMimopay(XLHRN); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // MPoint public void onClickMpoint(View view) { initMimopay(MPOINT); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Others public void onClickLastResult(View view) { initMimopay(LASTRESULT); } public void onClickSwitchGateway(View view) { initMimopay(STAGGATE); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Main codes of How to use Mimopay SDK. // // To have better understanding it is strongly recommend to refer to http://staging.mimopay.com/api documentation. // Before create Mimopay object, you need to fill parameters that is described in documentation. Values that is used // in this sample is our mimopay's internal test account. // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// boolean mQuietMode = false; Mimopay mMimopay = null; MimopayInterface mMimopayInterface = new MimopayInterface() { public void onReturn(String info, ArrayList<String> params) { String s,toastmsg = ""; dp("onReturn: " + info); if(params != null) { toastmsg += (info + "\n\n"); int i,j = params.size(); for(i=0;i<j;i++) { s = params.get(i); toastmsg += (s + "\n"); dp(String.format("[%d] %s", i, s)); } if(mQuietMode) { final String ftoastmsg = toastmsg; runOnUiThread(new Runnable() { public void run() { Toast.makeText(getApplicationContext(), ftoastmsg, Toast.LENGTH_LONG).show(); }}); } } } }; void initMimopay(int paymentid) { String emailOrUserId = "1385479814"; // this parameter is your user's unique id or user's email. Normally your app/game should have unique ID for every user String merchantCode = "ID-0031"; // for this parameter, after registration to mimopay, your should received this from us String productName = "ID-0031-0001"; // this parameter is also your own territory. It will be pass back to your server, either successful or an error occurs String transactionId = ""; // this should be unique in every transaction. If you leave it empty, SDK will generate unique numbers based on unix timestamp String secretKeyStaging = null; String secretKeyGateway = null; // You may initiate secretKeyStaging and secretKeyGateway hard-coded in your app's source code, however if this is not appropriate, you may use our // encrypted secretKey to avoid it. Every registerred merchant should received two files from us, jar file and txt file. Txt file contains secretKey's encrypted-key, // while the jar file contains secretKey's encrypted-value. So all you need to do is select and copy the encrypted-key from txt file, paste into Merchant.get() parameter, // it will return your real secretKey. try { secretKeyStaging = Merchant.get(true, "<KEY>); secretKeyGateway = Merchant.get(false, "<KEY>); } catch(Exception e) { dp("e: " + e.toString()); } String currency = "IDR"; if(secretKeyStaging == null || secretKeyGateway == null) { Toast.makeText(getApplicationContext(), "secretKey problem!", Toast.LENGTH_LONG).show(); return; } mMimopay = new Mimopay(getApplicationContext(), emailOrUserId, merchantCode, productName, transactionId, secretKeyStaging, secretKeyGateway, currency, mMimopayInterface); AlertDialog.Builder altbld = null; AlertDialog alert = null; // enableLog is Mimopay SDK's internal log print. If set to enable, all logs will printed out in your app's log. This is very usefull in your development phase mMimopay.enableLog(true); // By default, the payment process will goes to staging.mimopay.com. Keep it commented out while you are still in development phase, // when you are ready to production you can un-comment it, so SDK will goes to gateway.mimopay.com // mMimopay.enableGateway(mbGateway); mQuietMode = false; // As stated in Mobile SDK documentation, it support two modes, UI and Quiet mode. UI mode methods have no // parameter(s) in it while Quiet mode methods have. switch (paymentid) { case TOPUP: // // this will launch UI mode top up activity. One or more payment channels will be shown, may not be the same every merchants // mMimopay.executeTopup(); break; case SMARTFREN: // smartfren altbld = new AlertDialog.Builder(MainActivity.this); altbld.setMessage("Mimopay's SDK supports both, Default UI and Quiet Mode. " + "In Quiet Mode, the voucher number is currently set to 1234567890123456. " + "You may change it later in this sample source code.\n" + "Now, please choose which one.") .setCancelable(true) .setPositiveButton("UI", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // // this will launch UI mode top up activity and straight to show Smartfren channel. // mMimopay.executeTopup("smartfren"); }}) .setNegativeButton("Quiet", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mQuietMode = true; // // Running Smartfren top up quietly (quiet mode). The running background task will straight call for Smartfren channel, // and do the top up with the number that passed in the second parameter. No UI will pops up. // You will notified the result via MimopayInterface.onReturn, check its 'info' string status // mMimopay.executeTopup("smartfren", "1234567890123456"); }}); alert = altbld.create(); alert.setTitle("Smartfren Topup"); alert.setIcon(android.R.drawable.stat_notify_error); alert.show(); break; case SEVELIN: // sevelin altbld = new AlertDialog.Builder(MainActivity.this); altbld.setMessage("Mimopay's SDK supports both, Default UI and Quiet Mode. " + "In Quiet Mode, the voucher number is currently set to 1234567890123456. " + "You may change it later in this sample source code.\n" + "Now, please choose which one.") .setCancelable(true) .setPositiveButton("UI", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // // UI mode for sevelin, straight to show Sevelin channel // mMimopay.executeTopup("sevelin"); }}) .setNegativeButton("Quiet", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mQuietMode = true; // // Running Sevelin top up quietly. You will notified the result via MimopayInterface.onReturn // check its 'info' string status // mMimopay.executeTopup("sevelin", "1234567890123456"); }}); alert = altbld.create(); alert.setTitle("Sevelin Topup"); alert.setIcon(android.R.drawable.stat_notify_error); alert.show(); break; case ATM: // ATM mMimopay.executeATMs(); break; case BCA: // ATM BCA altbld = new AlertDialog.Builder(MainActivity.this); altbld.setMessage("Mimopay's SDK supports both, Default UI and Quiet Mode. " + "In Quiet Mode, the value of mimocard is currently set to 50K. " + "You may change it later in this sample source code.\n" + "Now, please choose which one.") .setCancelable(true) .setPositiveButton("UI", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mMimopay.executeATMs("atm_bca"); }}) .setNegativeButton("Quiet", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mQuietMode = true; mMimopay.executeATMs("atm_bca", "50000"); }}); alert = altbld.create(); alert.setTitle("ATM BCA"); alert.setIcon(android.R.drawable.stat_notify_error); alert.show(); break; case BERSAMA: // ATM Bersama altbld = new AlertDialog.Builder(MainActivity.this); altbld.setMessage("Mimopay's SDK supports both, Default UI and Quiet Mode. " + "In Quiet Mode, the value of mimocard is currently set to 50K. " + "You may change it later in this sample source code.\n" + "Now, please choose which one.") .setCancelable(true) .setPositiveButton("UI", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mMimopay.executeATMs("atm_bersama"); }}) .setNegativeButton("Quiet", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mQuietMode = true; mMimopay.executeATMs("atm_bersama", "50000"); }}); alert = altbld.create(); alert.setTitle("ATM Bersama"); alert.setIcon(android.R.drawable.stat_notify_error); alert.show(); break; case UPOINT: // upoint altbld = new AlertDialog.Builder(MainActivity.this); altbld.setMessage("Mimopay's SDK supports both, Default UI and Quiet Mode. " + "In Quiet Mode, the UPoint credits is currently set to 1000 and phone number is 081219106541. " + "You may change them later in this sample source code.\n" + "Now, please choose which one.") .setCancelable(true) .setPositiveButton("UI", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mMimopay.executeUPointAirtime(); }}) .setNegativeButton("Quiet", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mQuietMode = true; mMimopay.executeUPointAirtime("1000", "081219106541", false); }}); alert = altbld.create(); alert.setTitle("UPoint Airtime"); alert.setIcon(android.R.drawable.stat_notify_error); alert.show(); break; case XL: // XL mMimopay.executeXL(); break; case XLAIRTIME: // XL Airtime altbld = new AlertDialog.Builder(MainActivity.this); altbld.setMessage("Mimopay's SDK supports both, Default UI and Quiet Mode. " + "In Quiet Mode, the XL Airtime credits is currently set to 10000 and phone number is 087771270843. " + "You may change them later in this sample source code.\n" + "Now, please choose which one.") .setCancelable(true) .setPositiveButton("UI", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mMimopay.executeXLAirtime(); }}) .setNegativeButton("Quiet", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mQuietMode = true; mMimopay.executeXLAirtime("10000", "087771270843", false); //Toast.makeText(getApplicationContext(), "not yet implemented", Toast.LENGTH_LONG).show(); }}); alert = altbld.create(); alert.setTitle("XL Airtime"); alert.setIcon(android.R.drawable.stat_notify_error); alert.show(); break; case XLHRN: // XL HRN altbld = new AlertDialog.Builder(MainActivity.this); altbld.setMessage("Mimopay's SDK supports both, Default UI and Quiet Mode. " + "In Quiet Mode, the voucher number (HRN) is currently set to 1234567890123456. " + "You may change it later in this sample source code.\n" + "Now, please choose which one.") .setCancelable(true) .setPositiveButton("UI", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mMimopay.executeXLHrn(); }}) .setNegativeButton("Quiet", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mQuietMode = true; mMimopay.executeXLHrn("1234567890123456"); }}); alert = altbld.create(); alert.setTitle("XL HRN"); alert.setIcon(android.R.drawable.stat_notify_error); alert.show(); break; case MPOINT: // mpoint altbld = new AlertDialog.Builder(MainActivity.this); altbld.setMessage("Mimopay's SDK supports both, Default UI and Quiet Mode. " + "In Quiet Mode, the MPoint Airtime credits is currently set to 200 and phone number is XXXXXXXX. " + "You may change them later in this sample source code.\n" + "Now, please choose which one.") .setCancelable(true) .setPositiveButton("UI", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { AlertDialog.Builder altbld = new AlertDialog.Builder(MainActivity.this); altbld.setMessage("Choose your language ?\n(Dutch language here just an example)") .setCancelable(true) .setPositiveButton("English", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mMimopay.executeMPointAirtime(); }}) .setNegativeButton("Dutch", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Please note that payment methods those are in Bahasa by default, cannot be customized. // Since MPoint is in English by default, you can do as below if you want to customized to other language. // Please refer to CustomLang.java, it shows how all words should be managed. mMimopay.setUiLanguage(CustomLang.mDutch); mMimopay.executeMPointAirtime(); }}); AlertDialog aldlg = altbld.create(); aldlg.setTitle("Language"); aldlg.setIcon(android.R.drawable.stat_notify_error); aldlg.show(); }}) .setNegativeButton("Quiet", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mQuietMode = true; mMimopay.executeMPointAirtime("200", "0126296221", false); //Toast.makeText(getApplicationContext(), "not yet implemented", Toast.LENGTH_LONG).show(); }}); alert = altbld.create(); alert.setTitle("MPoint Airtime"); alert.setIcon(android.R.drawable.stat_notify_error); alert.show(); break; case LASTRESULT: String s = ""; int ires = 0; String [] sarr = mMimopay.getLastResult(); if(sarr != null) { ires = sarr.length; for(int i=0;i<ires;i++) { s += (sarr[i] + "\n"); } } //String toastmsg = String.format("ires=%d\ns=%s", ires, s); Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show(); break; case STAGGATE: mbGateway = !mbGateway; Button btn = (Button) findViewById(R.id.btnswitchgateway); btn.setText(mbGateway ? "Switch to Staging" : "Switch to Gateway"); Toast.makeText(getApplicationContext(), "SDK will points to " + (mbGateway ? "Gateway" : "Staging") + " on next transaction", Toast.LENGTH_LONG).show(); break; } } }
f6f55faad9311382d5d8c366476e9582badabade
[ "Markdown", "Java" ]
3
Java
oxenprogrammer/Mimopay-Android-SDK
46397b99590d79aef1a10f18bda6714351d35ea6
e7867b8ea9a88f8c549910120f75a96c85e761b4
refs/heads/master
<file_sep>package com.lizhidu.appdesign.utils; import android.content.Context; import android.widget.Toast; /** * Created by yz on 2015/7/2. */ public class ToastUtils { // public static void showLong(String msg){ // makeTextLong(context,msg); // } public static void makeTextLong(Context context, String message) { Toast.makeText(context, message, Toast.LENGTH_LONG).show(); } public static void makeTextShort(Context context, String message) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } } <file_sep>package com.lizhidu.appdesign; import android.app.Dialog; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.Toast; /** */ public class BaseActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } /** * 弹出toast 显示时长short * * @param pMsg */ protected void showToastMsgShort(String pMsg) { Toast.makeText(this, pMsg, Toast.LENGTH_SHORT).show(); } /** * 弹出toase 显示时长long * * @param pMsg */ protected void showToastMsgLong(String pMsg) { Toast.makeText(this, pMsg, Toast.LENGTH_LONG).show(); } }
fe0ea244730a58258f25bc73523983d8faa6a8bc
[ "Java" ]
2
Java
lizhidu/AppDesign
88ec7d5ed3fce5a0447baabf5400f22224ba9e9f
7f27d18746a48b1ac67226ae6ae3858e96391a3d
refs/heads/master
<file_sep>import java.io.*; import java.util.*; public class OrderProcessor { private int orderId, partNum, quanity; private double price, tax, shipping, total; //no generic constructor is needed, as it will not be used. public OrderProcessor(int order1, int partNum1, int quanity1, double price1) { //Will hold all variables orderId=order1; partNum=partNum1; quanity=quanity1; price=price1; //parts to be calculated tax=calcTax(); shipping=calcShipping(); total=addTotal(); } public double calcTax(){ //find tax, 2% rate return (price*quanity)*.02; } public double calcShipping(){ //find shipping, calcuated before taxes, 5% rate return (price*quanity)*.05; } public double addTotal(){ //add all applicable variables together return (price*quanity)+tax+shipping; } public void OrdersProcessed()throws IOException{ //Will create the output file FileWriter fileOut = new FileWriter("D:\\CS2\\JavaBPA\\OrderProcessor_HunterBrown\\OrdersProcessed.txt"); PrintWriter out= new PrintWriter(fileOut); out.println("Order Id: "+orderId); out.println("Part Num: "+partNum); out.println("Price: "+price); out.println("Quanity: "+quanity); out.println("Tax: "+tax); out.println("Shipping: "+shipping); out.println("Total: "+total); out.close(); } /*Example Ouput Order Id: 1 Part Num: 111 Price: 4.99 Quantity: 3 Tax: 0.2994 Shipping: 0.7485 Total: 16.0179 */ } <file_sep> import java.util.*; import java.io.*; public class main { private static int orderId, partNum, quanity; private static double price; public static void main(String [] args) throws IOException{ System.out.println("Start processing orders."); //strings from input file into numbers read(); //test case OrderProcessor test = new OrderProcessor(orderId,partNum,quanity,price); test.OrdersProcessed(); System.out.println("Finished processing orders"); } public static void read() throws IOException{ //will read input into usable variables Scanner fileIn= new Scanner(new File("Orders.txt")); String line = fileIn.nextLine(); String [] variables= new String[4]; int count=0; // will be used to keep track of spot in variables. //I dont know how the inpurt file will actually look, so just incase. if(line.compareTo("ORDER_ID|PART_NUM|PRICE|QUANTITY")) line=fileIn.nextLine(); for(int i=0; i<line.length();i++){ //will take apart string and input only the numbers into 'variables' int loc = line.indexOf("|",i); if(loc==-1) loc=line.length(); variables[count]= line.substring(i,loc); count++; i=loc; } fileIn.close(); //variables -to-> numbers orderId=Integer.parseInt(variables[0]); partNum=Integer.parseInt(variables[1]); quanity=Integer.parseInt(variables[3]); price=Double.parseDouble(variables[2]); } } <file_sep>import java.util.*; import java.io.*; public class main { public static void main(String [] args) throws IOException { WordSearch roon= new WordSearch(); roon.fillGridNonsense(); roon.fillUsedGrid(); roon.setGrid(); roon.fillGridSpaces(); roon.fileWriting(); System.out.println(roon); } } <file_sep>import java.io.File; import java.io.IOException; import java.util.Scanner; import static java.lang.System.*; public class Lab21g { public static void main( String args[] ) throws IOException { Scanner kb = new Scanner(new File("lab21g.dat")); do{ int size = kb.nextInt(); kb.nextLine(); Maze doug = new Maze(size,kb.nextLine()); doug.hasExitPath(0,0); System.out.println(doug); System.out.println("\n\n\n---------------------------------"); }while(kb.hasNextLine()); } } <file_sep>import java.util.*; public class connectFour { //General String [][] board = new String [6][7]; private Scanner kbs = new Scanner(System.in); int turn = (int)(Math.random()*(2-1+1)+1); int turns=1; //Variables tied to the Win checking String [][] counted= new String [6][7]; int lastX; int lastY; int wturns=0; boolean play = true; public connectFour() { fillSpaces(); } public void fillSpaces(){ //Blank the board for(int i=0; i<6;i++){ for(int j=0; j<7;j++){ board[i][j]=" "; } } } public void blankCounted(){ //reset counted grid and winTurns Counter. wturns=0; for(int i=0; i<6;i++){ for(int j=0; j<7;j++){ counted[i][j]=" "; } } //blank after every win check } public boolean inbounds(int x, int y){ if(x>=0 && x<6 && y>=0 && y<7){ return true; } else return false; } public void playGame2(){ //2player Game Here while(play){ boardPrint(); if(turn==1){ System.out.println("Player One's turn."); System.out.println("\n\n\n\n\n\n\n\n\n\n"); move(); counted[lastX][lastY]="1"; if(win(1,lastX,lastY,0, "X")){ boardPrint(); System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n----------------------------\nCONGRATS PLAYER ONE!!! You won in: "+turns+" turns!!\n----------------------------"); play=false; } blankCounted(); turn++; turns++; } else if(turn==2){ System.out.println("Player Two's turn."); System.out.println("\n\n\n\n\n\n\n\n\n\n"); move(); counted[lastX][lastY]="1"; if(win(1,lastX,lastY,0, "O")){ boardPrint(); System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n----------------------------\nCONGRATS PLAYER TWO!!! YOU WIN!\n----------------------------"); play=false; } blankCounted(); turn--; turns++; } } } public void move(){ // where the move will occur int col; do{ System.out.println("Which Column?"); col= kbs.nextInt()-1; }while(col<0 || col>7); if(board[0][col].compareTo(" ")>0){ System.out.println("Pick a different Column."); move(); } else{ int x=5; //potential problem, -1 thing when while(board[x][col].compareTo(" ")>0 && x>=0){ x--; } lastX=x; lastY=col; if(turn==1) board[x][col]="X"; else if(turn==2) board[x][col]="O"; } } public boolean win(int count, int x, int y, int type, String player){ //Method Usage //Using it: win(1,lastX,lastY,0, "X" or "O") // WILL CHECK IN THIS ORDER: HORIZONTAL (Left/Right) , VERTICAL (Up/Down) , DIAGONAL (Left/Right)(Up/Down) //Type: 0=N/A, 1=Left/ 2=Right, 3=Up/4=Down, 5=Left-Up Diag/ 6= Right-Down Diag, 7 Right-Up Diag 8 Left-Down Diag //System.out.println("X:"+x+" Y:"+y+" Type:"+type+" Count:"+count);//remove if(wturns>=2){ //Checks for infinite looping back and forth blankCounted(); return false; } if(turns<6){ blankCounted(); return false; } else if(count==4){ return true; } else{ //left if(type==0 || type==1){ if(inbounds(x,y-1) ){ if(board[x][y-1].equals(player)){ if(counted[x][y-1].compareTo("1")!=0){ counted[x][y-1]="1"; return win(count+1,x,y-1,1,player); } else{ wturns++; return win(count,x,y-1,2,player); } } } else{ //blankCounted();//potential //counted[lastX][lastY]="1"; return win(count, lastX, lastY,2,player); //REMEMBER RETURN THE GOD DAMN COUNT FOR CORRECT PAIRINGS SO IT DOESNT RESET TO 1. } } } //right if(type==0 || type ==2){ if(inbounds(x,y+1)){ if(board[x][y+1].equals(player)){ if(counted[x][y+1].compareTo("1")!=0){ counted[x][y+1]="1"; return win(count+1,x,y+1,1,player); } else{ wturns++; return win(1, lastX, lastY,3,player); //return win(count,x,y+1,1,player); } } } else{ blankCounted(); counted[lastX][lastY]="1"; return win(1, lastX, lastY,3,player); } } //up if(type==0 || type==3){ if(inbounds(x+1,y)){ if(board[x+1][y].equals(player)){ if(counted[x+1][y].compareTo("1")!=0){ counted[x+1][y]="1"; return win(count+1,x+1,y,3,player); } else{ wturns++; return win(count,x+1,y,4,player); } } } } //down if(type==0 || type==4){ if(inbounds(x-1,y)){ if(board[x-1][y].equals(player)){ if(counted[x-1][y].compareTo("1")!=0){ counted[x-1][y]="1"; return win(count+1,x-1,y,4,player); } else{ wturns++; return win(1, lastX, lastY,5,player); // return win(count,x-1,y,4,player); } } } else return win(1, lastX, lastY,5,player); //Make it go down the list check for the FOURRSS } //diagonals... //Left-Up if(type==0 || type ==5){ if(inbounds(x-1,y-1)){ if(board[x-1][y-1].equals(player)){ if(counted[x-1][y-1].compareTo("1")!=0){ counted[x-1][y-1]="1"; return win(count+1,x-1,y-1,1,player); } else{ wturns++; return win(count,x-1,y-1,6,player); } } } else{ blankCounted(); counted[lastX][lastY]="1"; return win(1, lastX, lastY,6,player); } } //Right-down if(type==0 || type ==6){ if(inbounds(x+1,y+1)){ if(board[x+1][y+1].equals(player)){ if(counted[x+1][y+1].compareTo("1")!=0){ counted[x+1][y+1]="1"; return win(count+1,x+1,y+1,1,player); } else{ wturns++; return win(1, lastX, lastY,7,player); //return win(count,x+1,y+1,6,player); } } } else{ blankCounted(); counted[lastX][lastY]="1"; return win(1, lastX, lastY,7,player); } } //Right-Up if(type==0 || type ==7){ if(inbounds(x-1,y+1)){ if(board[x-1][y+1].equals(player)){ if(counted[x-1][y+1].compareTo("1")!=0){ counted[x-1][y+1]="1"; return win(count+1,x-1,y+1,7,player); } else{ wturns++; return win(count,x-1,y+1,8,player); } } } else{ blankCounted(); counted[lastX][lastY]="1"; return win(1, lastX, lastY,8,player); } } //Left-Down if(type==0 || type ==8){ if(inbounds(x+1,y-1)){ if(board[x+1][y-1].equals(player)){ if(counted[x+1][y-1].compareTo("1")!=0){ counted[x+1][y-1]="1"; return win(count+1,x+1,y-1,8,player); } else{ wturns++; return false;//return win(count,x,y,8,player); } } } else{//final failure blankCounted(); return false; } } return false; } public void boardPrint(){ System.out.println("\n\n\n----------------------------"); System.out.println(" 1 2 3 4 5 6 7"); for(int i=0; i<6;i++){ for(int j=0; j<7;j++){ System.out.print("[ "+board[i][j]+" ]"); } System.out.println(); } } } <file_sep>Projects ======== Big projects I have created during my time in Computer Science in HS. Lab21g: Recursive Maze solver. Finds if there is an exit path, count the shortest amount of steps required and highlights the path. Connect Four: Connect four, win checking done recursively. Project made on my own. Play connect four, currently developing an AI for it. Word Search: Recursive 12x12 random word search generator. Creates a text file which can be printed and solved. == Most projects are solved object oriented approach.
e1bbf949ffbfd8778e5f060899b3e3f218845189
[ "Markdown", "Java" ]
6
Java
Biiliam/Projects
bdaa90e2f8bc815e87f731bf53c9bb1564989402
123dedc7b1e9e2915cf36d111bf6030a82243389
refs/heads/master
<repo_name>Justin8428/multicon<file_sep>/man/inner.outer.Rd \name{inner.outer} \alias{inner.outer} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Comparing Within-set and Between-set Correlations } \description{ Returns the average within-set correlation and average between-set correlation for a given list of sets of variables. } \usage{ inner.outer(L) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{L}{ \code{The argument 'L' is a list of data.frames with each data.frame containing the the items or variables that are thought to belong together} } } \details{ When doing factor analysis, principal components analysis, or cluster analysis of items one might desire to know how well the items thought to belong to a factor, component, or cluster (or set) correlate amongst each other as opposed to items thought to belong to other factors, components, or clusters (sets). This function returns for each factor, componnet, or cluster its average "inner" correlation and its average "outer" correlation. For more information on logic of this strategy see Rosenthal and Rosnow (2008) under "Principal Components." } \value{ Returns a data.frame with 2 rows indicating the average within-set (inner) correlation and average between-set (outer) correlation respectively. The number of columns is equal to length of "L" representing the results for each set. \item{Inner t }{The average correlation amongst items in that set.} \item{Outer r}{The average correlation of items between sets.} %% ... } \references{ Rosenthal, R. & Rosnow, R. R. (2007). Essentials of Behavioral Research: Methods and Data Analysis (3rd ed.). New York: McGraw-Hill. } \author{ <NAME> } \seealso{ \code{\link{MTMM}}, ~~~ } \examples{ # We can generate some random data by first creating a population correlation matrix sig <- matrix(c(1.00, .4, .6, .05, .1, -.05, .4, 1.00, .5, .08, -.02, .03, .6, .5, 1.00, .09, .1, -.07,.05, .08, .09, 1.00, .6, .7, .1, -.02, .1, .6, 1.00, .5, -.05, .03, -.07, .7, .5, 1.00), ncol=6, byrow=TRUE) sig library(mvtnorm) # Now create random data based on this population matrix d <- rmvnorm(100, sigma=sig) #Create a list indicating the items belonging to each set L <- list(d[,1:3], d[,4:6]) #Now use inner.outer on that list inner.outer(L) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ Factor Structure } <file_sep>/man/splithalf.r.Rd \name{splithalf.r} \alias{splithalf.r} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Split-half Correlation and Reliability } \description{ Estimates the split-half correlation and reliability for a given set of items in matrix or data.frame x. This function finds the average of the randomly split-half correlation for a data.frame() of items. It also returns the reliability (speaman-brown) which should be equivalent to cronbach's alpha. Assumes the split-halves are exactly halves or as close to it as possible. } \usage{ splithalf.r(x, sims = 1000, graph = TRUE, seed = 2) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ A matrix or data.frame containing the items or variables for which one wants to estimate the splithalf reliability } \item{sims}{ A numeric value indicating the number of splithalf reliabilities to compute of which the mean will be used as the best estimate. } \item{graph}{ A logical element indicating whether graphical output should be returned. } \item{seed}{ A numeric element specifying the random seed to be used. If set to FALSE, no seed is used. } } \details{ The columns of x are randomly divided into two equal halves, a scale mean is computed for each half, and then the two sets of scale means are correlated to estimate a splithalf correlation. The splithalf correlation is adjusted by the spearman-brown prophecy formula to create a splithalf reliability. This procedure is repated 'sims' times and the mean of the splithalf correlations (Avg.r) is returned as the best estimate of the reliability of a single item, while the mean of the splithalf reliabilities (Rel) is returned as the best estimate of the reliability of the composite of all items. The SD of the reliability estimate (standard error in this case) is also returned. } \value{ A matrix summarizing the results: \item{N Vars}{ The number of variables in x } \item{Mean Split-Half r}{ The average of all split-half correlations } \item{Rel}{ The average of all split-half reliabilities } \item{Rel SD}{ The standard deviation of all split-half reliabilities } } \author{ <NAME> } \seealso{ \code{\link{vector.splithalf}} } \examples{ data(bfi.set) # Imagine we are forming a composite extraversion variable from the eight # extraversion items in BFI.set # Three items need to be reverse scored sBFI6r <- 6 - bfi.set$sBFI6 sBFI21r <- 6 - bfi.set$sBFI21 sBFI31r <- 6 - bfi.set$sBFI31 # Now put them all into one data.frame ext.vars <- data.frame(bfi.set$sBFI1, sBFI6r, bfi.set$sBFI11, bfi.set$sBFI16, sBFI21r, bfi.set$sBFI26, sBFI31r, bfi.set$sBFI36) head(ext.vars) # Looks good # Now compute the splithalf reliability for a possible composite splithalf.r(ext.vars, sims=100) # Note in practice sims = 1000 or more might be preffered # Should be close to the value resulting from alpha alpha.cov(cov(ext.vars, use="p")) # Getting the 'exact' splithalf correlation and reliability # by computing the splithalf correlation for all possible halves # (for comparison purposes) combs <- combn(8,4) out <- rep(NA, ncol(combs)) for(i in 1:ncol(combs)) { c1 <- composite(ext.vars[,combs[,i]]) c2 <- composite(ext.vars[,-c(combs[,i])]) out[i] <- cor(c1,c2) } mean(out) # Exact splithalf correlation mean(out*2/(out+1)) # Exact splithalf reliability } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ split-half } \keyword{ reliability }% __ONLY ONE__ keyword per line <file_sep>/man/lensModel.rd \name{lensModel} \alias{lensModel} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Lens Model Regressions } \description{ A function for computing key statistics from a Lens Model (Brunswick, 1952) analysis.} \usage{ lensModel(inSet, exSet, cueSet) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{inSet}{A data.frame containing the variables on the validity side of the lens model. It must have the same dimensions as exSet and columns corresponding to the columns in exSet.} \item{exSet}{A data.frame containing the variables on the utilization side of the lens model. It must have the same dimensions as inSet and columns corresponding to the columns in inSet.} \item{cueSet}{A data.frame containing the cues to use in the lens analysis.} } \details{This function is designed to perform so-called Lens Model analyses. If a set of targets has known criterion values on some dimensions (e.g., self-reports of personality) a set of judges may make judgments of those targets (e.g., other reports of personality) based on some information (i.e., Cues) presented to the judges (e.g., some behavioral acts). A lens model analyses examines (a) the achievement of the judges (i.e., accuracy) for each dimension being judged as the correlation between the judgments and the criterion, (b) the validities of the cues for each dimension as the linear regression coefficients predicting the criterion from all of the cues, and (c) the cue utilization of the judges for each dimension as the linear regression coefficients predicting the judgments from the cues. This function computes all of this and much more in one step. } \value{ Returns a list containing the following \item{Lens Stats}{A data.frame containing the following statistics for each variable in inSet:} \enumerate{ \item{Validity Saturation}{The multiple R for the Validity side of the Lens Model} \item{Utilization Saturation}{The multiple R for the Utilization side of the Lens Model} \item{Coefficient Correlation}{The correlation between the Cue Validities and the Cue Utilizations (not including the intercept)} \item{Achievement}{The correlation between inSet and exSet} \item{Linear Knowledge}{The correlation between the fitted values from the validity and utilization sides of the model} \item{Unmodeled Knowledge}{The correlation between the residuals from the validity and utilization sides of the model} } \item{Cue Validities}{A data.frame of size ncol(cueSet)+1 X ncol(inSet) containing the regression coefficients (including intercept) for the validity side of the lens model.} \item{Cue Utilizations}{A data.frame of size ncol(cueSet)+1 X ncol(exSet) containing the regression coefficients (including intercept) for the utilization side of the lens model.} %% ... } \references{ <NAME>. (1952). The conceptual framework of psychology. Chicago: University of Chicago Press } \author{ <NAME> } \seealso{ \code{\link{lensDetect}} \code{\link{print.lensMod}} } \examples{ data(lensData) DIAMONDS.in <- lensData[,32:39] # Self-ratings on 8 Situation Characteristics DIAMONDS.ex <- lensData[,40:47] # Coder-ratings on 8 Situation Characteristics CUES <- lensData[,3:31] # Coded Situation Cues mod <- lensModel(DIAMONDS.in, DIAMONDS.ex, CUES) # Get the lens statistics mod$'Lens Stats' # View the overall stats print(mod) # View the individual coefficients and p-values } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{Lens Model} <file_sep>/man/acq1.Rd \name{acq1} \alias{acq1} \docType{data} \title{ Aquaintance (Number 1) CAQ ratings } \description{ This is an aquaintance rating of a participant's personality in the Riverside Situation Project. } \usage{data(acq1)} \format{ A data frame with 205 observations on the following 100 variables. \describe{ \item{\code{acq1CAQ001}}{Critical, skeptical, not easily impressed} \item{\code{acq1CAQ002}}{A genuinely dependable and responsible person} \item{\code{acq1CAQ003}}{Has a wide range of interests} \item{\code{acq1CAQ004}}{Talkative} \item{\code{acq1CAQ005}}{Behaves in a giving way toward others} \item{\code{acq1CAQ006}}{Fastidious, perfectionistic} \item{\code{acq1CAQ007}}{Favors conservative values} \item{\code{acq1CAQ008}}{Appears to have a high degree of intellectual capacity} \item{\code{acq1CAQ009}}{Uncomfortable with uncertainty and complexity} \item{\code{acq1CAQ010}}{Anxiety and tension find outlet in bodily symptoms} \item{\code{acq1CAQ011}}{Protective of those close to him or her} \item{\code{acq1CAQ012}}{Tends to be self-defensive} \item{\code{acq1CAQ013}}{Thin-skinned; sensitive to criticism or interpersonal slight} \item{\code{acq1CAQ014}}{Genuinely submissive; accepts domination comfortably} \item{\code{acq1CAQ015}}{Skilled in social techniques of imaginative play, pretending, and humor} \item{\code{acq1CAQ016}}{Introspective and concerned with self as an object} \item{\code{acq1CAQ017}}{Sympathetic and considerate} \item{\code{acq1CAQ018}}{Initiates humor} \item{\code{acq1CAQ019}}{Seeks reassurance from others} \item{\code{acq1CAQ020}}{Has a rapid personal tempo; behaves and acts quickly} \item{\code{acq1CAQ021}}{Arouses nurturant feelings in others} \item{\code{acq1CAQ022}}{Feels a lack of personal meaning in life} \item{\code{acq1CAQ023}}{Extrapunitive; tends to transfer or project blame} \item{\code{acq1CAQ024}}{Prides self on being objective,rational} \item{\code{acq1CAQ025}}{Tends toward over-control of needs and impulses} \item{\code{acq1CAQ026}}{Productive; gets things done} \item{\code{acq1CAQ027}}{Shows condescending behavior in relations with others} \item{\code{acq1CAQ028}}{Tends to arouse liking and acceptance } \item{\code{acq1CAQ029}}{Turned to for advice and reassurance} \item{\code{acq1CAQ030}}{Gives up and withdraws where possible in the face of frustration and adversity} \item{\code{acq1CAQ031}}{Regards self as physically attractive} \item{\code{acq1CAQ032}}{Aware of the impression made on others} \item{\code{acq1CAQ033}}{Calm, relaxed in manner} \item{\code{acq1CAQ034}}{Over-reactive to minor frustrations, irritable} \item{\code{acq1CAQ035}}{Has warmth; has the capacity for close relationships; compassionate} \item{\code{acq1CAQ036}}{Subtly negativistic; tends to undermine and obstruct } \item{\code{acq1CAQ037}}{Guileful and deceitful, manipulative, opportunistic} \item{\code{acq1CAQ038}}{Has hostility toward others} \item{\code{acq1CAQ039}}{Thinks and associates ideas in unusual ways; has unconventional thought processes} \item{\code{acq1CAQ040}}{Vulnerable to real or fancied threat, generally fearful} \item{\code{acq1CAQ041}}{Moralistic} \item{\code{acq1CAQ042}}{Reluctant to commit to any definite course of action; tends to delay or avoid action} \item{\code{acq1CAQ043}}{Facially and/or gesturally expressive} \item{\code{acq1CAQ044}}{Evaluates the motivation of others in interpreting situations} \item{\code{acq1CAQ045}}{Has a brittle ego-defense system; does not cope well under stress or strainr} \item{\code{acq1CAQ046}}{Engages in personal fantasy and daydreams} \item{\code{acq1CAQ047}}{Has a readiness to feel guilt} \item{\code{acq1CAQ048}}{Keeps people at a distance; avoids close interpersonal relationships} \item{\code{acq1CAQ049}}{Basically distrustful of people in general} \item{\code{acq1CAQ050}}{Unpredictable and changeable in behavior and attitudes} \item{\code{acq1CAQ051}}{Genuinely values intellectual and cognitive matters} \item{\code{acq1CAQ052}}{Behaves in an assertive fashion} \item{\code{acq1CAQ053}}{Unable to delay gratification} \item{\code{acq1CAQ054}}{Emphasizes being with others; gregarious} \item{\code{acq1CAQ055}}{Self-defeating} \item{\code{acq1CAQ056}}{Responds to humor} \item{\code{acq1CAQ057}}{Interesting, arresting person} \item{\code{acq1CAQ058}}{Enjoys sensuous experiences (touch, taste, smell, physical contact)} \item{\code{acq1CAQ059}}{Concerned with own body and adequacy of physiological functioning} \item{\code{acq1CAQ060}}{Has insight into own motives and behavior} \item{\code{acq1CAQ061}}{Creates and exploits dependency in people} \item{\code{acq1CAQ062}}{Tends to be rebellious and non-conforming} \item{\code{acq1CAQ063}}{Judges self and other in conventional terms} \item{\code{acq1CAQ064}}{Socially perceptive of a wide range of interpersonal cues} \item{\code{acq1CAQ065}}{Pushes and tries to stretch limits} \item{\code{acq1CAQ066}}{Enjoys esthetic impressions; is esthetically reactive} \item{\code{acq1CAQ067}}{Self-indulgent} \item{\code{acq1CAQ068}}{Basically anxious} \item{\code{acq1CAQ069}}{Sensitive to anything that can be construed as a demand} \item{\code{acq1CAQ070}}{Behaves in an ethically consistent manner} \item{\code{acq1CAQ071}}{Has high aspiration level for self} \item{\code{acq1CAQ072}}{Concerned with own adequacy as a person} \item{\code{acq1CAQ073}}{Tends to perceive many different contexts in sexual terms} \item{\code{acq1CAQ074}}{Subjectively unaware of self-concern; feels satisfied with self} \item{\code{acq1CAQ075}}{Has a clear-cut, internally consistent personality} \item{\code{acq1CAQ076}}{Projects feelings and motivations onto others} \item{\code{acq1CAQ077}}{Appears straightforward, forthright, candid in dealing with others} \item{\code{acq1CAQ078}}{Feels cheated and victimized by life; self-pitying} \item{\code{acq1CAQ079}}{Ruminates and has persistent, preoccupying thoughts} \item{\code{acq1CAQ080}}{Interested in members of the opposite sex} \item{\code{acq1CAQ081}}{Physically attractive; good-looking} \item{\code{acq1CAQ082}}{Has fluctuating moods} \item{\code{acq1CAQ083}}{Able to see to the heart of important problems} \item{\code{acq1CAQ084}}{Cheerful} \item{\code{acq1CAQ085}}{Emphasizes communication through action and non-verbal behavior} \item{\code{acq1CAQ086}}{Repressive and dissociative tendencies; denies unpleasant thoughts and conflicts} \item{\code{acq1CAQ087}}{Interprets basically simple and clear-cut situations in complicated and particularizing ways} \item{\code{acq1CAQ088}}{Personally charming} \item{\code{acq1CAQ089}}{Compares self to others} \item{\code{acq1CAQ090}}{Concerned with philosophical problems} \item{\code{acq1CAQ091}}{Power-oriented; values power in self and others} \item{\code{acq1CAQ092}}{Has social poise and presence; appears socially at ease} \item{\code{acq1CAQ093}}{Behaves in gender-appropriate masculine or feminine style and manner} \item{\code{acq1CAQ094}}{Expresses hostile feelings directly} \item{\code{acq1CAQ095}}{Tends to offer advice} \item{\code{acq1CAQ096}}{Values own independence and autonomy} \item{\code{acq1CAQ097}}{Emotionally bland; has flattened affect} \item{\code{acq1CAQ098}}{Verbally fluent; can express ideas well} \item{\code{acq1CAQ099}}{Self-dramatizing; histrionic} \item{\code{acq1CAQ100}}{Does not vary roles; relates to everyone in the same way} } } \details{ Subjects are listed as Rows (N=205). CAQ items (\code{\link{caq.items}}) (100 items) } \source{ \url{http://psy2.fau.edu/~shermanr/index.html} } \references{ <NAME>., <NAME>., & <NAME>. (2010). Situational similarity and personality predict behavioral consistency. Journal of Personality and Social Psychology, 99(2), 330-343 } \examples{ data(acq1) head(acq1) #aquaintance 1 } \keyword{datasets} <file_sep>/man/scoreTest.Rd \name{scoreTest} \alias{scoreTest} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Scoring Multiple Tests, Scales, or Composites } \description{ A function for scoring tests, measures, or questionnaires } \usage{ scoreTest(items, keys, Zitems = FALSE, maxScore = NULL, minScore = NULL, rel = FALSE, nomiss = .8, tr = 0, item.names = NULL, check.keys=TRUE) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{items}{ A data.frame containing the items or questions on the test or measure. } \item{keys}{ A list containing the scoring keys for each scale or construct to be scored from the test or measure. Each object in the list consists of a single numeric vector indicating the column position of 'items' belonging to that scale. Placing a negative sign in front of the column number indicates that this item should be reverse scored. } \item{Zitems}{ A logical indicating whether the items should be standardized (Z-scored) prior to the computation of scale scores. } \item{maxScore}{ A numeric element indicating the maximum possible score on the scales used to rate the items. Useful when (a) there are items that need to be reverse scored and (b) the maximum score on a rating scale is never used. In all other cases this is not needed. } \item{minScore}{ A numeric element indicating the minimum possible score on the scales used to rate the items. Useful when (a) there are items that need to be reverse scored and (b) the minimum score on a rating scale is never used. In all other cases this is not needed. } \item{rel}{ A logical indicating whether reliability statistics should be computed for each scale. } \item{nomiss}{ A numeric between 0 and 1 indicating the proportion of the data that must be present to compute a scale score for a particular observation. Any subject with fewer than this proportion of valid data points will recieve NA. } \item{tr}{ A numeric between 0 and 1 indicating the amount of trimming to be done when computing a scale score. } \item{item.names}{ A character vector indicating the names for the items. If left NULL, the names provided in keys will be used. } \item{check.keys}{ A logical indicating whether, when calculating reliabilities, the function should check for items negatively correlated with the scale and automatically reverse them for the alpha calculation. Generally, with this function items should already be scored in the proper direction. Thus, this serves as a warning that items may be miskeyed. } } \details{ This function computes mean scores for each of the scales provided in the keys list. If rel=TRUE, it also computes the reliabilites for the composite scores based on the keys list. } \value{ If rel=FALSE, then a matrix containing the composite or scale scores is returned. If rel=TRUE, a list containing... \item{rel}{The reliability statistics for each composite or scale} \item{scores}{The composite or scale scores.} } \author{ <NAME> } \seealso{ \code{\link{plotProfile}} \code{\link{meanif}} \code{\link{scoreItems}} } \examples{ data(bfi) keys.list <- list("agree"=c(-1,2,3,4,5), "conscientious"=c(6,7,8,-9,-10),"extraversion"=c(-11,-12,13,14,15), "neuroticism"=c(16,17,18,19,20),"openness"=c(21,-22,23,24,-25)) out <- scoreTest(bfi, keys.list, nomiss=0, maxScore=6, minScore=1) outZ <- scoreTest(bfi, keys.list, Zitems=TRUE, nomiss=0) describe(out) # Descriptives of Scale Scores describe(outZ) outR <- scoreTest(bfi, keys.list, nomiss=0, rel=TRUE, maxScore=6) outR$rel # Scale reliabilities } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ item scoring } \keyword{ composite }% __ONLY ONE__ keyword per line <file_sep>/man/insitu.Rd \name{insitu} \alias{insitu} \docType{data} \title{Internal Situation Ratings} \description{ These are self-ratings of 10 situations (columns) actually experienced by participants (one rater per situation) on 8 characteristics (rows). } \usage{data(insitu)} \format{ A matrix containing ratings of 10 situations (columns) on 8 characteristics (rows). } \details{ Situations are the columns (N=10) and characteristics are the rows. } \references{ <NAME>., <NAME>., & <NAME>. (forthcoming). Foundations of situation perception: Towards a psychology of how people form impressions of situations. European Journal of Personality. } \examples{ data(insitu) insitu } \keyword{datasets}<file_sep>/man/egraph.Rd \name{egraph} \alias{egraph} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Plotting Summary Statistics with Error Bars } \description{ A function for plotting a summary statistics with error bars. } \usage{ egraph(DV, grp = NULL, plotFUN = mean, errFUN = c("ci", "se", "sd"), sides = 2, conf = 0.95, xpoints = NULL, grp.names = NULL, tick = FALSE, ylim = NULL, len = 0, ...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{DV}{ A numeric variable containing raw scores to be summarized in the graph. } \item{grp}{ Either (a) a single variable indicating the grouping factor, (b) a list of variables each indicating a different grouping factors, or (c) NULL (default) in which case only a single bar is graphed. } \item{plotFUN}{ The function used to create the summary statistic. Usually mean is desired. } \item{errFUN}{ A character element indicating the type of error bars to be calculated. There are four possible choices: "ci" (the default) uses a confidence interval for the mean with level indicated by the conf= argument. "se" uses 1 Standard Error from the mean. "sd" uses 1 Standard Deviation from the mean. NULL indicates no error bars are desired. } \item{sides}{ A numeric indicating whether one-sided or two-sided error bars are desired. } \item{conf}{ A numeric between .00 and 1.00 indicating the desired level of confidence if type "ci" is used for the errFUN argument. } \item{xpoints}{ A vector indicating the location on the x-axis for each group. Can be used to create space between certain groups. } \item{grp.names}{ A character vector providing the names for the different groups (conditions). } \item{tick}{ A logical indicating whether tick marks should be drawn on the x-axis for each group. } \item{ylim}{ A numeric vector of length 2 indicating the lower and upper limits of the y-axis. } \item{len}{ A numeric indicating the desired length of the error bar "caps" in inches. } \item{\dots}{ Other arguments passed to the plot() function including graphing parameters. } } \details{ This function plots a summary statistic with error bars using raw data as input. This is different from, and often more convenient, than barplot() which requires the use to compute the values to be plotted and error bars outside of the function. This is a preferred form of presenting group means (rather than bargraphs) because bargraphs tend to suggest more accuracy than in reality (Cumming, 2012).} \references{ <NAME>. (2012). Understanding the New Statistics: Effect Sizes, Confidence Intervals, and Meta-Analysis. New York: Routledge. } \author{ <NAME> } %% ~Make other sections like Warning with \section{Warning }{....} ~ \seealso{ \code{\link{bargraph}} \code{\link{barplot}} } \examples{ #Making some random data y <- rnorm(100) x <- rep(c(1,2),50) z <- c(1,rep(c(1,2,3),33)) zz <- rep(c(1:4),25) x2 <- rep(1:2, each=50) #plotting egraph(y) egraph(y, xlab="", ylab="DV", las=1) egraph(y, x, xlab="Conditions", ylab="DV", las=1) egraph(y, z, xlab="Conditions", ylab="DV", las=1) egraph(y, zz, xlab="", ylab="DV", las=1, font.main=1, main="my title", sub="Arms Indicate 95 percent CIs") egraph(y, zz, xlab="Conditions", ylab="DV", las=1, font.main=1, main="my title", xpoints=c(1,1.5, 4,4.5),grp.names=c("A","B", "C", "D"), sub="Arms Indicate 95 percent CIs", sides=1) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ descriptive statistics } \keyword{ plot }% __ONLY ONE__ keyword per line <file_sep>/man/vector.alpha.Rd \name{vector.alpha} \alias{vector.alpha} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Alpha Replicability of a Vector (pattern) of Correlations } \description{ A function for compute the alpha replicability of a vector of linear coefficients (e.g. correlations, covariances) between a single variable (x) and a set of other variables (set).} \usage{ vector.alpha(x, set, type = "cor", CI = 0.95, CItype = "xci", minval = -1) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ A numeric vector of the same length as nrow(set). } \item{set}{ A data.frame or matrix of which each column is to be related with x. } \item{type}{ A character string specifying the type of linear coefficients between x and set to be computed. The default "cor" computes the replicability for the correlations between x and set. The option "cov" computes the replicability for covariances. The option "XY" computes the replicability for the betas when X predicts Y. The option "YX" computes the replicability for the betas when Y predicts X. } \item{CI}{ A numeric between .00 and 1.00 indicating the desired confidence level. } \item{CItype}{ A character string of either "xci" or "aci" specifying the the type of confidence interval to compute based on Koning & Franses (2003). } \item{minval}{ A numeric indicating the minimum level of replicability to be returned. } } \details{ Sherman and Wood (2014) suggest that one way to estimate the replicability of a vector of correlation coefficients between a variable of interest (x) and a set of other variables (set) is to 1) Z-score all variables, 2) multiply the Z-scored variable of interest by the Z-scores for each of the variables in set, 3) transpose the resultant matrix of cross-products and compute cronbach's alpha on this matrix. This function does just that and includes options for getting replicability coefficients for regression slopes and covariances. } \value{ \item{N }{The sample size} \item{Average R }{The average magnitude of correlations between x and set } \item{Alpha }{The estimated alpha reliability } \item{Upper Limit }{The Upper Limit of the CI around the split-half reliability} \item{Lower Limit }{The Lower Limit of the CI around the split-half reliability} } \references{ <NAME>. & <NAME>. (2014). Estimating the expected replicability of a pattern of correlations and other measures of association. Multivariate Behavioral Research. 49(1), 17-40. <NAME>. & <NAME>. (2003). Confidence Intervals for Cronbach's Alpha Coefficient values. ERIM Report Series Reference No. ERS-2003-041-MKT. Available at SSRN: http//ssrn.com/abstract=423658 } \author{ <NAME> } \seealso{ \code{\link{vector.splithalf}} \code{\link{splithalf.r}} } \examples{ data(RSPdata) # Is the pattern of relationships between self reported #extraversion and behavior replicable? RSPdata$sEXT data(beh.comp) head(beh.comp) vector.alpha(RSPdata$sEXT, beh.comp) #alpha = .666 # Might also try vector.splithalf vector.splithalf(RSPdata$sEXT,beh.comp) # split-half reliability = .684 } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ replicability } \keyword{ alpha }% __ONLY ONE__ keyword per line <file_sep>/man/meanif.Rd \name{meanif} \alias{meanif} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Mean } \description{ Returns the mean of a vector, matrix, or data.frame if it has nomiss proportion of valid cases } \usage{ meanif(set, nomiss = 0.8, tr = 0) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{set}{ A vector, matrix, or data.frame } \item{nomiss}{ A numeric vector specifying the proporiton of valid cases in set (i.e. data that must not be NA) for the mean to be returned } \item{tr}{ A numeric specifying the amount of trimming if desired } } \details{ The built in r function mean includes an na.rm argument that allows the computation of a mean excluding missing cases. However, sometimes one wants to calculate the mean of an object so long as some proportion of those cases are present. The nomiss option of this function allows this capability. If fewer than the nomiss proportion of the cases are invalid (i.e. misssing) the function will return NA. Otherwise, it will return the mean of the valid cases. } \value{ Returns the mean. } \author{ <NAME> } \seealso{ \code{\link{mean}} } \examples{ data(RSPdata) RSPdata$sEXT #no missing values meanif(RSPdata$sEXT,nomiss=1) RSPdata$sEXT[100] <- NA #now we make one value missing meanif(RSPdata$sEXT,nomiss=1) #returns NA meanif(RSPdata$sEXT,nomiss=.8) #returns value } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ mean } \keyword{ missing values }% __ONLY ONE__ keyword per line <file_sep>/man/Profile.resid.Rd \name{Profile.resid} \alias{Profile.resid} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Residuals } \description{ Computes the residuals for each observation (row) where items pairs are the corresponding columns in x.set and y.set. } \usage{ Profile.resid(x.set, y.set, nomiss = 0.8) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x.set}{ A data.frame or matrix, with the same dimensions as y.set, of which each row is a predictor of the corresponding row in y.set. } \item{y.set}{ A data.frame or matrix, with the same dimensions as x.set, of which each row is to be predicted by the correpsonding row in x.set. } \item{nomiss}{ A numeric between .00 and 1.00 specifying the proportion of x-y pairs required to be complete before NA is returned instead of the regression coefficients. The default of .80 means that if more than 20 percent of the x-y pairs are incomplete an NA will be returned. } } \details{ The residuals from predicting the values in each row of y.set from the values in the corresponding row of y.set are returned. If fewer than 'nomiss' of the x-y pairs of observations for a given row are valid (complete) then NA will be returned for all of that row's residuals. } \value{ Returns a data.frame of the same size as x.set containing the residual values of y.set after being predicted by x.set. } \author{ <NAME> } \seealso{ \code{\link{Profile.reg}} \code{\link{lin.coef}} } \examples{ data(acq1) data(caq) #Lets get the regression coeficients for predicting aquaintance #California Adult Q-Set (CAQ) personality ratings from #self-report CAQ ratings Profile.reg(caq,acq1) #We can look at the residuals from those regressions res.acq <- Profile.resid(acq1, caq) head(res.acq) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ Residual } \keyword{ Profile Agreement } \keyword{ Distinctiveness }% __ONLY ONE__ keyword per line <file_sep>/man/MTMM.Rd \name{MTMM} \alias{MTMM} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Multi Trait Multi Method Matrix } \description{ Returns the summary results from a multi-trait multi-method correlation matrix including the average correlations for Same Trait-Different Method, Same Method-Different Trait, and Different Method-Different Trait. } \usage{ MTMM(x, traits, methods) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ A data.frame organized such that each column represents the ratings for each Trait-Method combination. The columns must be ordered in sets such that the first set is the first trait rated by each method, followed by the second trait rated by each method (in the same order), and so on. } \item{traits}{ An integer indicating the total number of different traits rated. } \item{methods}{ An integer indicating the total number of methods used. } } \details{ Multi-trait Multi-method matrices are often used examine the validity of the construct(s) under investigation. That is, if different methods agree about a target's standing on a trait, it is more likely that the trait itself is valid. However, such agreement must be compared with agreement about different targets using the same method (method effects), which must in turn be compared with agreement about different targets using different methods (i.e., the general similarity of targets). This function returns all three such values: The average agreement about targets on the given traits using different methods, the average agreement about different targets using the same methods (method effects), and the average agreement about different targets using different methods (baseline agreement). } \value{ %% ~Describe the value returned %% If it is a LIST, use \item{SameTrait }{The average correlation for the Same Traits rated by Different Methods} \item{SameMethod }{The average correlation for the Same Methods used to rate the Different Traits} \item{DiffDiff}{The average correlation for the Different Traits rated by Different Methods} %% ... } \author{ <NAME> } %% ~Make other sections like Warning with \section{Warning }{....} ~ \seealso{ \code{\link{inner.outer}} } \examples{ # We can generate some random data by first creating a population correlation matrix sig <- matrix(c(1.00,.4,.6,.05,.1,-.05,.4,1.00,.5,.08, -.02,.03,.6,.5,1.00,.09,.1,-.07,.05,.08,.09,1.00,.6,.7,.1,-.02,.1,.6, 1.00,.5,-.05,.03,-.07,.7,.5,1.00), ncol=6, byrow=TRUE) sig library(mvtnorm) # Now create random data based on this population matrix d <- rmvnorm(100, sigma=sig) #Now use MTMM on this data.frame indicating that there are 2 traits and 3 methods. MTMM(d, 2, 3) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ multi trait multi method matrix} <file_sep>/man/Profile.r.rep.Rd \name{Profile.r.rep} \alias{Profile.r.rep} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Profile Correlation Replicability } \description{ Computes the replicability of both overall and distinctive Profile correlations. } \usage{ Profile.r.rep(x.set, y.set, nomiss = 1, CI = 0.95, CItype = "xci") } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x.set}{ A data.frame or matrix of the same dimensions as y.set with rows corresponding to the rows in y.set } \item{y.set}{ A data.frame or matrix of the same dimensions at x.set with rows correponsding to the rows in x.set } \item{nomiss}{ A numeric between .00 and 1.00 indicating the proportion of pairs of scores that must be valid for a result to be computed. } \item{CI}{ A numeric between .00 and 1.00 indicating the desired confidence level. } \item{CItype}{ A character element of either "xci" or "aci" specifying the the type of confidence interval to compute based on Koning & Franses (2003). } } \details{ Sherman and Wood (in press) describe a method for computing the replicability of a vector of correlation coefficients (see vector.alpha). They also discuss how this may be applied to profile correlations. This function applies the strategy outlined by Sherman and Wood (in press) and used by the vector.alpha function to profile correlations. The results include the replicability point estimate for both the overall profile correlations between x.set and y.set as well as the distinctive profile correlations. Confidence intervals are computed based on Koning and Frances' (2003) methods, choosing either asymptotic ("aci") or exact ("xci"). } \value{ A matrix containing the replicability point estimate and its confidence intervals. \item{Overall}{Replicability of Overall correlations between x.set and y.set} \item{Distinctive }{Replicability of Distinctive correlations between x.set and y.set} } \references{ <NAME>. & <NAME>. (in press). Estimating the expected replicability of a pattern of correlations and other measures of association. Multivariate Behavioral Research. } \author{ <NAME> } \seealso{ \code{\link{Profile.r}} \code{\link{vector.alpha}} } \examples{ data(acq1) data(caq) #Lets look at Profile correlations between self-report California Adult Q-Sort #ratings of personality and Aquaintance #ratings names(acq1) names(caq) # The basic Profile agreements Profile.r(caq, acq1) # Both overall and distinctive agreements Profile.r(caq, acq1, distinct = TRUE)$Agreement # How replicable (reliable) are those agreement patterns? Profile.r.rep(caq, acq1) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ replicability } \keyword{ distinctiveness } \keyword{ profile correlations }% __ONLY ONE__ keyword per line <file_sep>/man/sig.r.Rd \name{sig.r} \alias{sig.r} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Significance Levels for Correlations } \description{ Returns asterisks denoting statistical significance levels for a vector of correlations } \usage{ sig.r(r, n, tail) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{r}{ A numeric vector of correlation coefficients } \item{n}{ n the sample size associated with the vector of correlation coefficients } \item{tail}{ An integer of value 1 or 2 indicating whether a one-tailed (1) or two-tailed (2) significance level is to be used. } } \details{ This function is called by the q.cor function to put statistical significance levels next to the resulting correlations. } \value{ A symbol is returned to identify the significance level of a correlation coefficient. A value of " " denotes p > .1. A value of "+ " denotes p < .1. A value of "* " denotes p < .05. A value of "** " denotes p < .01. A value of "***" denotes p < .001. } \author{ <NAME> } \seealso{ \code{\link{q.cor}}, ~~~ } \examples{ # A correlation of r=.15 with a sample of 100 is significant #at p < .05 using a one-tailed t-test sig.r(r=.15,n=200,tail=1) # A correlation of r=.1 is trending toward significance at p < .1. sig.r(r=.1,n=200,tail=1) # Or it can be used on a vector. #This is helpful for displaying significance levels of results. v <- c( .1, .3, .4, .05, .04, .8) sig.labels <- sig.r(v, 200, 1) table1 <- data.frame(v, sig.labels) colnames(table1) <- c("r", "sig level") table1 } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ q.cor } \keyword{ significance } <file_sep>/man/item.resid.Rd \name{item.resid} \alias{item.resid} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Item Level Residuals } \description{ Returns the residuals of y.set after predicting the values from the corresponding columsn in x.set. } \usage{ item.resid(x.set, y.set, nomiss = 0.8) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x.set}{ A data.frame or matrix, with the same dimensions as y.set, of which each column is a predictor of the corresponding column in y.set. } \item{y.set}{ A data.frame or matrix, with the same dimensions as x.set, of which each column is to be predicted by the correpsonding column in x.set. } \item{nomiss}{ A numeric between .00 and 1.00 specifying the proportion of x-y pairs required to be complete before NA is returned instead of the regression coefficients. The default of .80 means that if more than 20 percent of the x-y pairs are incomplete an NA will be returned. } } \details{ Each column in x.set is used to predict its corresponding column in y.set and the residuals are returned. } \value{ A data.frame with the same dimensions as y.set, containing the residual values on each item after predicting the item scores from the values in x.set. } \author{ <NAME> } \seealso{ \code{\link{lin.coef}} \code{\link{temp.resid}} \code{\link{Profile.reg}} } \examples{ data(caq) data(RSPdata) #Lets predict California Adult Q-Sort scores from extraversion scores #and compute the residual scores on each CAQ item. head(caq) RSPdata$sEXT dim(caq) m.sEXT <- matrix(RSPdata$sEXT, nrow = 205, ncol = 100) head(m.sEXT) residuals <- item.resid(m.sEXT,caq) head(residuals) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{residuals } <file_sep>/man/lensData.rd \alias{lensData} \name{lensData} \docType{data} \title{Self and External Coder Ratings of Situations} \description{ This file contains data from 204 participants who rated their own situations using the RSQ. Those RSQ ratings were composited to form the 8 DIAMONDS situation characteristics. These situations were later rated on the same dimensions by external raters and then coded for a number of situation cues. } \usage{data(lensData)} \format{ A data.frame with 205 observations containing \describe{ \item{\code{SID}}{A participant ID number} \item{\code{Sex}}{The participant's sex} \item{\code{family}}{Was with one or more family members} \item{\code{mate}}{Was with mate or spouse} \item{\code{friend}}{Was with one or more friends} \item{\code{roomatesneighbor}}{Was with a roommate or a neighbor} \item{\code{group}}{Was with one or more colleagues/classmates, a group, or a team} \item{\code{alone}}{Was alone} \item{\code{sports}}{Sports were present} \item{\code{exam}}{Was taken an exam, test, midterm, or final} \item{\code{cooking}}{Someone was cooking} \item{\code{eating}}{Someone was eating} \item{\code{social}}{People were socializing, talking, communicating, or hanging out} \item{\code{movietv}}{There was a movie or TV} \item{\code{travel}}{Situation involved travel (e.g., a car, driving)} \item{\code{computer}}{Situaiton involed computers or the internet} \item{\code{videogames}}{Situation involved video game playing or watching} \item{\code{readingbook}}{Was reading a book} \item{\code{working}}{Involved working, learning, or getting things done} \item{\code{shopping}}{Involved shopping, buying, ordering, or paying for something} \item{\code{grooming}}{Involved grooming or getting ready for something} \item{\code{waiting}}{Involved waiting for someone or something} \item{\code{sleep}}{Involved sleeping, resting, or napping} \item{\code{musicdance}}{Involved music or dancing} \item{\code{telephone}}{Involved using the telephone} \item{\code{home}}{Was in one's home, own room, or house} \item{\code{bathroom}}{Was in the bathroom} \item{\code{kitchen}}{Was in the kitchen} \item{\code{bed}}{Was in one's bed} \item{\code{school}}{Was at school, a university, a library, or laboratory} \item{\code{cafe}}{Was at a bar, restaurant, or cafe} \item{\code{duty}}{Self-rated Duty composite score} \item{\code{intellect}}{Self-rated Intellect composite score} \item{\code{adversity}}{Self-rated Adversity composite score} \item{\code{mating}}{Self-rated Mating composite score} \item{\code{positivity}}{Self-rated Positivity composite score} \item{\code{negativity}}{Self-rated Negativity composite score} \item{\code{deception}}{Self-rated Deception composite score} \item{\code{sociality}}{Self-rated Sociality composite score} \item{\code{dutyRater}}{Self-rated Duty composite score} \item{\code{intellectRater}}{Coder-rated Intellect composite score} \item{\code{adversityRater}}{Coder-rated Adversity composite score} \item{\code{matingRater}}{Coder-rated Mating composite score} \item{\code{positivityRater}}{Coder-rated Positivity composite score} \item{\code{negativityRater}}{Coder-rated Negativity composite score} \item{\code{deceptionRater}}{Coder-rated Deception composite score} \item{\code{socialityRater}}{Coder-rated Sociality composite score} } } \details{ This file contains data from 204 participants who rated their own situations using the RSQ. Those RSQ ratings were composited to form the 8 DIAMONDS situation characteristics. Those are duty, intellect, adversity, mating, positivity, negativity, deception, and sociality. Later, an external set of raters (4 each) read the situations as described the participants and rated them on the RSQ. These external ratings were averaged and 8 DIAMONDS composites were formed. Finally, the situation descriptions were read and coded for the prescence (1) vs. absence (0) of 39 situation cues (e.g., with family vs not). } \references{ <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2014). The situational eight DIAMONDS: A taxonomy of major dimensions of situation characteristics. Journal of Personality and Social Psychology, 107(4), 677-718. } \examples{ data(lensData) head(lensData) } \keyword{datasets}<file_sep>/man/yuenContrast.rd \name{yuenContrast} \alias{yuenContrast} \alias{yuenContrast.default} \alias{yuenContrast.formula} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Generalized Yuen's T-tests } \description{ Computes a t-test for multiple groups using a generalization of Yuen's (1974) method for trimmed t-tests. In the case of K > 2 groups, a t-contrast use calculated based on the given contrast weights. } \usage{ yuenContrast(IV, ...) ## Default Method \method{yuenContrast}{default}(IV, DV, wgt = c(1, -1), tr = .2, alpha = .05, EQVAR = FALSE, alternative = "unequal", ...) ## Method for class 'formula' \method{yuenContrast}{formula}(formula, data = NULL, wgt = c(1, -1), tr = .2, alpha = .05, EQVAR = FALSE, alternative = "unequal", ...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{IV}{ A factor of the same length as DV containing the independent variable codes. } \item{DV}{ A numeric vector of the same length as IV containing the measured values. } \item{formula}{ A formula of the form lhs ~ rhs where lhs is a numeric vector containing the data values and rhs is a variable containing the corresponding groups. } \item{data}{ An optional data frame containing the variables in the formula. } \item{wgt}{ A numeric vector containing the contrast weights corresponding to each successive level of the IV. Defaults to c(1, -1), implying that the first group is expected to have a higher mean than the second. } \item{tr}{ A numeric element between .00 and < .50 specifying the amount of trimming to be used. } \item{alpha}{ A numeric element > .00 and < 1.00 specifying the Type I error rate. } \item{EQVAR}{ A logical indicating whether equal variances amongst the groups should be assumed. Defaults to FALSE (Yuen's Method). } \item{alternative}{ A character vector specifying the alternative hypothesis. Must be one of "unequal", "greater", or "less". } \item{...}{ Further arguments to be passed to or from methods. } } \details{ This function computes a t-value based on Yuen's (1974) method for calculating T for trimmed means if tr is greater than 0 and Welch's method for tr=0 and EQVAR=FALSE. The wgt option allows one to specify contrast weights to test hypotheses with more than 2 levels of an IV. By default it tests the hypothesis that two means are unequal. If a directional hypothesis is known ahead of time, use "greater" to predict that higher contrast weights have higher means and "less" to predict the opposite. A robust measure of the mean differences or the contrast is obtained by using some level of trimming. By setting the EQVAR option to TRUE degrees of freedom are consistent with Student's method. If EQVAR is FALSE (default) then degrees of freedom are calculated using the Welch-Sattertwaite approximation. The entire family of possible T-test equations can be found here: http://rynesherman.com/T-Family.doc } \value{A list containing... \item{Ms}{A data.frame with the sample size, mean, and weight for each group.} \item{test}{A data.frame with the test statistic (stat), the degrees of freedom (df), the critical value for the test statistic (crit), and the p-value} } \references{ <NAME>. (1974). The two-sample trimmed t for unequal population variances. Biometrika, 61, 165-170. Student (1908). The probable error of a mean. Bimetrika, 6, 1-25. } \author{ <NAME> } \seealso{ \code{\link{winvar}} \code{\link{t.test}} \code{\link{tContrast}} } \examples{ dv <- c(rnorm(30, mean=1, sd=2), rnorm(20)) iv <- c(rep(1,30),rep(2,20)) # Student's t-test (assuming equal variances) t.test(dv ~ iv, var.equal=TRUE) # Welch's t-test (not assuming equal variance) t.test(dv ~ iv, var.equal=FALSE) # Yuen's t-test with 20% trimming assuming equal variances yuenContrast(iv, dv, EQVAR=TRUE) # Yuen's t-test with 20% trimming not assuming equal variances yuenContrast(iv, dv, EQVAR=FALSE) # Same as Student's t-test using yuenContrast yuenContrast(iv, dv, EQVAR=TRUE, tr=0) # Same as Welch's t-test using yuenContrast yuenContrast(iv, dv, EQVAR=FALSE, tr=0) # Contrast with 3 Groups dv <- c(rnorm(30), rnorm(20, mean=-.5), rnorm(10, mean=-1)) iv <- c(rep("c",30), rep("b", 20), rep("a", 10)) # With no trimming (t-contrast with Welch-Sattertwaite DFs) yuenContrast(iv, dv, wgt=c(1, 0, -1), tr=0) # With 20% trimming yuenContrast(iv, dv, wgt=c(1, 0, -1), tr=.2) # With the formula method yuenContrast(dv ~ iv, wgt = c(1, 0, -1)) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ t test } \keyword{ contrast } \keyword{ robust } \keyword{ yuen }% __ONLY ONE__ keyword per line <file_sep>/man/partwhole.Rd \name{partwhole} \alias{partwhole} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Part-Whole Correlation } \description{ Returns the part-whole correlations between an item or the mean of all possible groups of nitems and the composite of the full set of items. } \usage{ partwhole(x, nitems = 1, nomiss = 0.8) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ A matrix or data.frame containing the variables (in columns) thought to form a composite. } \item{nitems}{ A numeric element indicating the number of items desired for each possible group of items. } \item{nomiss}{ A numeric between .00 and 1.00 indicating the proportion of scores that must be non-missing for each composite before a score of NA is returned. } } \details{ The purpose of this function is to determine which subset of items, when formed into a unit-weighted composite, most strongly correlate with both a unit-weighted and a components weighted composite of the full set of items. For example, if one has an 8 item scale and wants to reduce it to a 4 item scale, it might be interest to know which 4 items can be composited and correlate most highly with the composite from the full set of 8 items. It turns out there are 70 ways to form 4-item composites from 8 total items. This function creates all 70 of those composites and correlates each with both a unit weighted composite from the original 8 items and a components scored (1 principal component) composite of the original 8 items. One can then look at the output to determine which 4-item composite best correlated with the full scale composite. } \value{ A matrix with 2 rows and K columns where K is the number of possible subset combinations. The column names indicate which items (separated by an underline) make up the subset combination. The first row (UnitWgt) is the result using a unit weighted composite for the total set of items and the second row (Component) is the result using principle component scores for the total set of items. } \author{ <NAME> } \seealso{ \code{\link{composite}} } \examples{ data(bfi.set) # Imagine we want to find the best two-item composite that correlates # highest with the full 8 items available to measure extraversion. # Three (of the extraversion) items need to be reverse scored sBFI6r <- 6 - bfi.set$sBFI6 sBFI21r <- 6 - bfi.set$sBFI21 sBFI31r <- 6 - bfi.set$sBFI31 # Now put them all into one data.frame ext.vars <- data.frame(bfi.set$sBFI1, sBFI6r, bfi.set$sBFI11, bfi.set$sBFI16, sBFI21r, bfi.set$sBFI26, sBFI31r, bfi.set$sBFI36) head(ext.vars) # Looks good # Now compute the parwhole correlation for all possible 2-item composites partwhole(ext.vars, 2) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ part-whole correlation } \keyword{ composite }% __ONLY ONE__ keyword per line <file_sep>/man/popsd.Rd \name{popsd} \alias{popsd} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Population Standard Deviation } \description{ Returns the population standard deviation of x } \usage{ popsd(x, nomiss = 0.8) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ A numeric vector } \item{nomiss}{ A numeric between .00 and 1.00 specifying the proporiton of valid cases in x (i.e. data that must not be NA) for the sd to be returned } } \details{ R's built-in sd function divides the sum of the squared deviations from the mean by the number of observations minus 1 (N-1). However, there are times where one would prefer to use the formula with N in the denominator (e.g. if one is working with the entire population of scores). This function does just that. } \value{ This function returns the population standard deviation. } \author{ <NAME> } \seealso{ \code{\link{sd}} } \examples{ x <- rnorm(100, mean = 12, sd = 10) sd(x) #sample standard deviation popsd(x) #population standard deviation } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ standard deviation} \keyword{ population descriptive statistics }% __ONLY ONE__ keyword per line <file_sep>/man/valid.pairs.Rd \name{valid.pairs} \alias{valid.pairs} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Valid Pairs } \description{ Returns information about the number of valid X-Y pairs. } \usage{ valid.pairs(x, y) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ A vector of the same length as 'y' } \item{y}{ A vector of the same lenght as 'x' } } \details{ This function returns the total number of X-Y pairs, the number of X-Y pairs with at least one of the pairs missing a value, the number of X-Y pairs without either pair missing, and the percentage of total pairs that do not have either pair missing. Called by the Profile.r function. } \value{ A list containing the following: \item{Tot }{The total number of X-Y pais } \item{Miss }{The total number of X-Y pairs with at least one value missing} \item{Valid }{The total number of X-Y pairs with neither value missing} \item{Pct }{The percentage of X-Y pairs with neither value missing} } \author{ <NAME> } \seealso{ \code{\link{Profile.r}} } \examples{ # Making some data x.vect <- rnorm(100, m=0, sd=.5) y.vect <- rnorm(100, m=0, sd=.5) #checking valid pairs valid.pairs(x.vect,y.vect) #making some missing data x.vect[1:5] <- NA y.vect[95:100] <- NA #now checking valid pairs valid.pairs(x.vect,y.vect) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ valid pairs } \keyword{ missing data } <file_sep>/man/composite.Rd \name{composite} \alias{composite} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Composite } \description{ Returns a mean composite for each observation (row) in the set } \usage{ composite(set, R = NULL, Zitems = FALSE, maxScore = NULL, rel=FALSE, nomiss = 0.8, tr = 0) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{set}{ A matrix or data.frame of the scores in the columns to be averaged } \item{R}{ A numeric vector specifying the columns in set that should be reverse scored prior to averaging. } \item{Zitems}{ A logical indicating whether the items should be standardized (Z-scored) before creating a composite. This is probably most useful when items have been measured on different scales. } \item{maxScore}{ A numeric element indicating the maximum possible score on each scale. If R = NULL then this is not needed. If not provided, composite will try to find the maximum possible score on its own. } \item{rel}{ A logical indicating whether the reliability information (alpha, avg r, etc.) for the composite should be printed (not returned however). } \item{nomiss}{ A numeric vector specifying the proporiton of valid cases in set (i.e. data that must not be NA) for the mean to be returned } \item{tr}{ Amount of trimming to be done before calculating the mean } } \details{ This function is used to create a unit-weighted composite of the variables listed in the columns of the matrix or data.frame "set" for each row. The nomiss option lets one specify the proportion of valid cases required for the composite mean to be computed. By default, the mean is computed if at least 80 precent of the data in the the row are valid, the mean results otherwise NA results. } \value{ Returns a list of composite scores corresponding to each row of 'set' } \author{ <NAME> } \examples{ data(RSPdata) names(RSPdata) # Forming a composite: # We will form a composite extraversion variable using BFI scores. # First put the variables into one data.frame ext.vars <- data.frame(RSPdata$sBFI1, RSPdata$sBFI6, RSPdata$sBFI11, RSPdata$sBFI16, RSPdata$sBFI21, RSPdata$sBFI26, RSPdata$sBFI31, RSPdata$sBFI36) head(ext.vars) # Looks good # Three items need to be reverse scored ext.comp <- composite(ext.vars, R = c(2,5,7), rel = TRUE) ext.comp # Let's say we want to include the CAQ item "04 - Is a talkative Individual" in our # extraversion composite. But is is measured on a 1 to 9 scale while the BFI variables # are measured on a 1 to 5 scale. We should set Zitems=TRUE to Z-score all of the # items before compositing. ext.comp2 <- composite(data.frame(ext.vars, RSPdata$sCAQ004), R = c(2,5,7), rel= TRUE, Zitems = TRUE) describe(ext.comp2) # mean is zero } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{composite} <file_sep>/man/horn.Rd \name{horn} \alias{horn} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Horn's Parallel Analysis } \description{ Conduct's Horn's (1965) parallel analysis for determining the number of principal components } \usage{ horn(set, sims = 100, nomiss = 1, graph = TRUE) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{set}{ \code{A data.frame containing the variables to be analyzed} } \item{sims}{ \code{A numeric indicating the number simulated data sets to use} } \item{nomiss}{ \code{A numeric from 0 to 1.00 indicating the percentage of data that must be valid (non-missing) for each case for it to be included in the analysis.} } \item{graph}{ \code{A logical indicating whether the results should be displayed graphically or not} } } \details{ Horn's (1965) method of determining the number of factors to extract uses bootstrap style resampling of the original data matrix to create a sample data matrix. The eigenvalues for this data matrix are then computed and stored. This process is repeated "sims" times and the average of the resulting eigenvalues is taken to indicate the vector of eigenvalues that would be expected by random data. Horn suggested that one should extract as many factors as have eigenvalues greater than the eigenvalues expected by random data. } \value{ Prints the number of components suggested and the number of cases deleted due to missingness. If graph=T a Scree Plot is graphed. } \references{ <NAME>. (1965) A rationale and test for the number of factors in factor analysis. Psychometrika, 30, 179-185. } \author{ <NAME> } \seealso{ \code{\link[psych]{fa.parallel}} } \examples{ data(bfi.set) # the Big Five Personality Inventory horn(bfi.set) #now we can see how many components are suggested } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ Parallel Analysis } \keyword{ Components }% __ONLY ONE__ keyword per line <file_sep>/man/alpha.cov.Rd \name{alpha.cov} \alias{alpha.cov} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Cronbach's Alpha of Covariance Matrix } \description{ Returns Cronbach's alpha from a covariance matrix } \usage{ alpha.cov(sigma) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{sigma}{ A square covariance or correlation matrix } } \details{ If a correlation matrix is provided rather than a covariance matrix, the result is a standardized Cronbach's alpha } \value{ Returns Standardized alpha when a correlation matrix is the input, and returns Raw alpha when a covariance matrix is input. } \author{ <NAME> } \seealso{ \code{\link[psych]{alpha}} } \examples{ data(RSPdata) names(RSPdata) # Forming a composite: # We will first form a composite extraversion variable using # BFI scores. # Three items need to be reverse scored sBFI6r <- 6 - RSPdata$sBFI6 sBFI21r <- 6 - RSPdata$sBFI21 sBFI31r <- 6 - RSPdata$sBFI31 # Now put them all into one data.frame ext.vars <- data.frame(RSPdata$sBFI1, sBFI6r, RSPdata$sBFI11, RSPdata$sBFI16, sBFI21r, RSPdata$sBFI26, sBFI31r, RSPdata$sBFI36) head(ext.vars) # Looks good # Get the internal consistency stats using the alpha() function in the # psych package alpha(ext.vars) # We can also get alpha from the correlation/covariance matrices alpha.cov(cor(ext.vars)) # Standardized Alpha alpha.cov(cov(ext.vars)) # Raw Alpha } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ alpha } \keyword{ covariance }% __ONLY ONE__ keyword per line <file_sep>/man/rate.caq.Rd \name{rate.caq} \alias{rate.caq} \docType{data} \title{ CAQ Rating } \description{ This is a dataset of CAQ ratings of participants' personality completed by research assistants using likert type ratings. } \usage{data(rate.caq)} \format{ A data frame with 64 observations on the following 100 variables. \describe{ \item{\code{CAQ001}}{Critical, skeptical, not easily impressed} \item{\code{CAQ002}}{A genuinely dependable and responsible person} \item{\code{CAQ003}}{Has a wide range of interests} \item{\code{CAQ004}}{Talkative} \item{\code{CAQ005}}{Behaves in a giving way toward others} \item{\code{CAQ006}}{Fastidious, perfectionistic} \item{\code{CAQ007}}{Favors conservative values} \item{\code{CAQ008}}{Appears to have a high degree of intellectual capacity} \item{\code{CAQ009}}{Uncomfortable with uncertainty and complexity} \item{\code{CAQ010}}{Anxiety and tension find outlet in bodily symptoms} \item{\code{CAQ011}}{Protective of those close to him or her} \item{\code{CAQ012}}{Tends to be self-defensive} \item{\code{CAQ013}}{Thin-skinned; sensitive to criticism or interpersonal slight} \item{\code{CAQ014}}{Genuinely submissive; accepts domination comfortably} \item{\code{CAQ015}}{Skilled in social techniques of imaginative play, pretending, and humor} \item{\code{CAQ016}}{Introspective and concerned with self as an object} \item{\code{CAQ017}}{Sympathetic and considerate} \item{\code{CAQ018}}{Initiates humor} \item{\code{CAQ019}}{Seeks reassurance from others} \item{\code{CAQ020}}{Has a rapid personal tempo; behaves and acts quickly} \item{\code{CAQ021}}{Arouses nurturant feelings in others} \item{\code{CAQ022}}{Feels a lack of personal meaning in life} \item{\code{CAQ023}}{Extrapunitive; tends to transfer or project blame} \item{\code{CAQ024}}{Prides self on being objective,rational} \item{\code{CAQ025}}{Tends toward over-control of needs and impulses} \item{\code{CAQ026}}{Productive; gets things done} \item{\code{CAQ027}}{Shows condescending behavior in relations with others} \item{\code{CAQ028}}{Tends to arouse liking and acceptance } \item{\code{CAQ029}}{Turned to for advice and reassurance} \item{\code{CAQ030}}{Gives up and withdraws where possible in the face of frustration and adversity} \item{\code{CAQ031}}{Regards self as physically attractive} \item{\code{CAQ032}}{Aware of the impression made on others} \item{\code{CAQ033}}{Calm, relaxed in manner} \item{\code{CAQ034}}{Over-reactive to minor frustrations, irritable} \item{\code{CAQ035}}{Has warmth; has the capacity for close relationships; compassionate} \item{\code{CAQ036}}{Subtly negativistic; tends to undermine and obstruct } \item{\code{CAQ037}}{Guileful and deceitful, manipulative, opportunistic} \item{\code{CAQ038}}{Has hostility toward others} \item{\code{CAQ039}}{Thinks and associates ideas in unusual ways; has unconventional thought processes} \item{\code{CAQ040}}{Vulnerable to real or fancied threat, generally fearful} \item{\code{CAQ041}}{Moralistic} \item{\code{CAQ042}}{Reluctant to commit to any definite course of action; tends to delay or avoid action} \item{\code{CAQ043}}{Facially and/or gesturally expressive} \item{\code{CAQ044}}{Evaluates the motivation of others in interpreting situations} \item{\code{CAQ045}}{Has a brittle ego-defense system; does not cope well under stress or strainr} \item{\code{CAQ046}}{Engages in personal fantasy and daydreams} \item{\code{CAQ047}}{Has a readiness to feel guilt} \item{\code{CAQ048}}{Keeps people at a distance; avoids close interpersonal relationships} \item{\code{CAQ049}}{Basically distrustful of people in general} \item{\code{CAQ050}}{Unpredictable and changeable in behavior and attitudes} \item{\code{CAQ051}}{Genuinely values intellectual and cognitive matters} \item{\code{CAQ052}}{Behaves in an assertive fashion} \item{\code{CAQ053}}{Unable to delay gratification} \item{\code{CAQ054}}{Emphasizes being with others; gregarious} \item{\code{CAQ055}}{Self-defeating} \item{\code{CAQ056}}{Responds to humor} \item{\code{CAQ057}}{Interesting, arresting person} \item{\code{CAQ058}}{Enjoys sensuous experiences (touch, taste, smell, physical contact)} \item{\code{CAQ059}}{Concerned with own body and adequacy of physiological functioning} \item{\code{CAQ060}}{Has insight into own motives and behavior} \item{\code{CAQ061}}{Creates and exploits dependency in people} \item{\code{CAQ062}}{Tends to be rebellious and non-conforming} \item{\code{CAQ063}}{Judges self and other in conventional terms} \item{\code{CAQ064}}{Socially perceptive of a wide range of interpersonal cues} \item{\code{CAQ065}}{Pushes and tries to stretch limits} \item{\code{CAQ066}}{Enjoys esthetic impressions; is esthetically reactive} \item{\code{CAQ067}}{Self-indulgent} \item{\code{CAQ068}}{Basically anxious} \item{\code{CAQ069}}{Sensitive to anything that can be construed as a demand} \item{\code{CAQ070}}{Behaves in an ethically consistent manner} \item{\code{CAQ071}}{Has high aspiration level for self} \item{\code{CAQ072}}{Concerned with own adequacy as a person} \item{\code{CAQ073}}{Tends to perceive many different contexts in sexual terms} \item{\code{CAQ074}}{Subjectively unaware of self-concern; feels satisfied with self} \item{\code{CAQ075}}{Has a clear-cut, internally consistent personality} \item{\code{CAQ076}}{Projects feelings and motivations onto others} \item{\code{CAQ077}}{Appears straightforward, forthright, candid in dealing with others} \item{\code{CAQ078}}{Feels cheated and victimized by life; self-pitying} \item{\code{CAQ079}}{Ruminates and has persistent, preoccupying thoughts} \item{\code{CAQ080}}{Interested in members of the opposite sex} \item{\code{CAQ081}}{Physically attractive; good-looking} \item{\code{CAQ082}}{Has fluctuating moods} \item{\code{CAQ083}}{Able to see to the heart of important problems} \item{\code{CAQ084}}{Cheerful} \item{\code{CAQ085}}{Emphasizes communication through action and non-verbal behavior} \item{\code{CAQ086}}{Repressive and dissociative tendencies; denies unpleasant thoughts and conflicts} \item{\code{CAQ087}}{Interprets basically simple and clear-cut situations in complicated and particularizing ways} \item{\code{CAQ088}}{Personally charming} \item{\code{CAQ089}}{Compares self to others} \item{\code{CAQ090}}{Concerned with philosophical problems} \item{\code{CAQ091}}{Power-oriented; values power in self and others} \item{\code{CAQ092}}{Has social poise and presence; appears socially at ease} \item{\code{CAQ093}}{Behaves in gender-appropriate masculine or feminine style and manner} \item{\code{CAQ094}}{Expresses hostile feelings directly} \item{\code{CAQ095}}{Tends to offer advice} \item{\code{CAQ096}}{Values own independence and autonomy} \item{\code{CAQ097}}{Emotionally bland; has flattened affect} \item{\code{CAQ098}}{Verbally fluent; can express ideas well} \item{\code{CAQ099}}{Self-dramatizing; histrionic} \item{\code{CAQ100}}{Does not vary roles; relates to everyone in the same way} } } \source{ \url{http://psy2.fau.edu/~shermanr/index.html} } \references{ <NAME>., & <NAME>. (2013). A methodological note on ordered q-sort ratings. Journal of Research in Personality, 47(12), 853-858 } \examples{ data(rate.caq) head(rate.caq) } \keyword{datasets} <file_sep>/man/alpha.aci.Rd \name{alpha.aci} \alias{alpha.aci} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Alpha Confidence Interval } \description{ Computes the asymptotic confidence interval for Cronbach's alpha following the method outlined by Koning & Franses (2003). } \usage{ alpha.aci(x, k, n, CI = 0.95) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ An alpha coefficient to compute a confidence interval around. } \item{k}{ The number of items on which alpha was computed. } \item{n}{ The number of sampling units (observations) on which alpha was computed. } \item{CI}{ A numeric element between .00 and 1.00 indicating the desired confidence level. } } \details{ Koning & Franses (2003) describe several methods for computing confidence intervals around Cronbach's alpha coefficient. This function returns what Koning and Franses (2003) refer to as the asymptotic confidence interval for alpha. The confidence interval is asymptomic and not necessarily symmetrical. For more info, see Koning and Franses (2003). } \value{ \item{Lower Limit }{Lower limit of confidence interval} \item{Upper Limit }{Upperlimit of confidence interval } } \references{ <NAME>. & <NAME>. (2003). Confidence Intervals for Cronbach's Alpha Coefficient values. ERIM Report Series Reference No. ERS-2003-041-MKT. Available at SSRN: http//ssrn.com/abstract=423658 } \author{ <NAME> } \seealso{ \code{\link{alpha.xci}} \code{\link{vector.alpha}} } \examples{ #Compute the asymptotic CI for an observed Cronbach's alpha #of .7 on 200 observaitons from a 10 item scale' alpha.aci(.7,10,200) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{alpha} \keyword{confidence interval}% __ONLY ONE__ keyword per line <file_sep>/man/cor.comb.rep.Rd \name{cor.comb.rep} \alias{cor.comb.rep} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Replicabilities and Correlations } \description{ A function for getting the replicabilities for cor.comb() correlations See cor.comb() and vector.splithalf() for more information. } \usage{ cor.comb.rep(x1, x2, x3, x4, set1, set2, set3, set4, sims = 100, CI = 0.95) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x1}{ vector paired with set1 } \item{x2}{ vector paired with set2 } \item{x3}{ vector paired with set3 } \item{x4}{ vector paired with set4 } \item{set1}{ matrix paired with x1 } \item{set2}{ matrix paired with x2 } \item{set3}{ matrix paired with x3 } \item{set4}{ matrix paired with x 4 } \item{sims}{ Number of simulations to be run in the randomization test (100 by default). } \item{CI}{ Desired confidence interval limits. Default is .95. } } \value{ \item{N }{The sample size. *See 'note'} \item{Rep }{Estimated replicability} \item{SE}{Standard Error of the estimated replicability} \item{UL }{Upper limit of the CI} \item{LL }{Lower limit of the CI} } \author{ <NAME> } \note{ Be wary that this function bases the reported "N" on the N of x1. } %% ~Make other sections like Warning with \section{Warning }{....} ~ \seealso{ \code{\link{cor.comb}} \code{\link{vector.splithalf}} } \examples{ data(RSPdata) names(RSPdata) #Computing the relationship between self reported extraversion and #Behavior measured by RBQ1 "Interviews others"over 4 situations data(rbqv3.items) rbqv3.items # the RBQ content # The correlations between extraversion and RBQ001 in Situation 1 cor(RSPdata$sEXT,RSPdata$v2rbq001) cor(RSPdata$sEXT,RSPdata$v3rbq001) # ... Situation 2 cor(RSPdata$sEXT,RSPdata$v4rbq001) # ... Situation 3 cor(RSPdata$sEXT,RSPdata$v5rbq001) # ... Situation 4 #now to use cor.comb to combine meta-analytically cor.comb(y1=RSPdata$sEXT,y2=RSPdata$sEXT,y3=RSPdata$sEXT,y4=RSPdata$sEXT, x1=RSPdata$v2rbq001,x2=RSPdata$v3rbq001,x3=RSPdata$v4rbq001,x4=RSPdata$v5rbq001) #now to test the replicability of these results data(v2rbq) data(v3rbq) data(v4rbq) data(v5rbq) # Note in practice sims = 100 or more might be preferred cor.comb.rep(x1=RSPdata$sEXT,x2=RSPdata$sEXT,x3=RSPdata$sEXT, x4=RSPdata$sEXT,set1=v2rbq,set2=v3rbq,set3=v4rbq,set4=v5rbq, sims=5) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ vector replicability } \keyword{ meta-analysis }% __ONLY ONE__ keyword per line <file_sep>/man/q.cor.print.Rd \name{q.cor.print} \alias{q.cor.print} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Print q.cor } \description{ This function is now deprecated. Please use print instead. Prints the results of a q.cor object in a more interpretable fashion. Also includes a convenient export option. } \usage{ q.cor.print(obj, var.content, initial, rnd = 2, EXPORT = FALSE, short = FALSE) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{obj}{ An object returned by the q.cor() function. } \item{var.content}{ A vector containing the content of the items or variables used as the "set" in a q.cor analysis. } \item{initial}{ A character element indicating the initial letters for the item codes or names in set. } \item{rnd}{ A numeric element specifying the number of places to round each correlation coefficient. } \item{EXPORT}{ A file location to export the print results. If FALSE (default) no exportation is done. } \item{short}{ A logical indicating whether long output (default) or short output is to be returned. } } \details{ This function serves as a compliment to the q.cor() function by summarizing the results of a q.cor object. This function easily adds the content of the items to the correlation table, sorts the correlation table, and allows the user to limit the table to only those items that are statistically significant at the p < .10 for the combined or .05 level for each gender by setting the short option = TRUE. In addition, the export option allows the user to output the results (either long or short) into a .csv file. } \author{ <NAME> } \seealso{ \code{\link{q.cor}} } \examples{ data(rbqv3.items) data(RSPdata) data(v2rbq) names(v2rbq) q.obj <- q.cor(RSPdata$sEXT, v2rbq, sex = RSPdata$ssex, fem = 1, male = 2, sims = 1000) #It might be necessary to adjust size of the width of your console to make this content fit. q.cor.print(q.obj, rbqv3.items, initial = "RBQ", short = TRUE, EXPORT = FALSE) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ q.cor } \keyword{ print }% __ONLY ONE__ keyword per line <file_sep>/man/winvar.rd \name{winvar} \alias{winvar} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Winsorized Variance } \description{ Returns the winsorized variance of x. } \usage{ winvar(x, tr = .2, na.rm = TRUE) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ A numeric vector of which to get the winsorized variance } \item{tr}{ The proportion of scores to winsorize } \item{na.rm}{ A logical indicating whether missing values should be removed prior to calculation. } } \details{ This function is borrowed directly from the {WRS} package.} \value{ Returns the winsorized variance of x based on tr percente winsorizing. } \author{ <NAME> } \seealso{ \code{\link{var}} } \examples{ x <- rnorm(20) var(x) winvar(x) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ robust } \keyword{ winsorized variance } \keyword{ variance }% __ONLY ONE__ keyword per line <file_sep>/man/print.lensMod.rd \name{print.lensMod} \alias{print.lensMod} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Printing Lens Model Output } \description{ A function for succinctly organizing output from the \code{\link{lensModel}} function. } \usage{ \method{print}{lensMod}(x, rnd.coef = 2, rnd.p = 3, ...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{A object of class LensMod to be printed} \item{rnd.coef}{A numeric indicating the number of digits to round the coefficients} \item{rnd.p}{A numeric indidating the number of digits to round the p-values} \item{...}{More arguments to pass to the print function.} } \details{ A print function for the \code{\link{lensModel}} function that makes the output easier to interpret. } \author{ <NAME> } \seealso{ \code{\link{lensModel}} } \examples{ data(lensData) DIAMONDS.in <- lensData[,32:39] # Self-ratings on 8 Situation Characteristics DIAMONDS.ex <- lensData[,40:47] # Coder-ratings on 8 Situation Characteristics CUES <- lensData[,3:31] # Coded Situation Cues mod <- lensModel(DIAMONDS.in, DIAMONDS.ex, CUES) # Get the lens statistics print(mod) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ Lens Model } <file_sep>/man/lensDetect.rd \name{lensDetect} \alias{lensDetect} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Signal Detection Analyses for Lens Model Output } \description{ A function for computing signal detection statistics from an object of class LensMod. } \usage{ lensDetect(x, crit) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{An object of class LensMod.} \item{crit}{A critical p-value for the validity and utilization coefficients to be deemed to be "valid" and "utilized" for the purposes of the signal detection analysis. Those cues with p-values less than crit will be deemed valid.} } \details{ A data.frame containing the Signal Detection outputs (see Fielding & Bell, 1997). } \value{ A data.frame containing the Signal Detection outputs (see Fielding & Bell, 1997). } \references{ <NAME>., & <NAME>. (1997). A review of methods for assessment of prediction errors in conservation presence/absence models. Environmental Conservation, 24(1), 38-49. } \author{ <NAME> } \seealso{ \code{\link{lensModel}} \code{\link{print.lensMod}} } \examples{ data(lensData) DIAMONDS.in <- lensData[,32:39] # Self-ratings on 8 Situation Characteristics DIAMONDS.ex <- lensData[,40:47] # Coder-ratings on 8 Situation Characteristics CUES <- lensData[,3:31] # Coded Situation Cues mod <- lensModel(DIAMONDS.in, DIAMONDS.ex, CUES) # Get the lens statistics lensDetect(mod) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ Lens Model } \keyword{ Signal Detection } <file_sep>/man/describe.r.Rd \name{describe.r} \alias{describe.r} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Descriptive Statistics for Correlations } \description{ Returns the descriptive statistics for a vector, matrix, or data.frame of correlation coefficients stored in x by using fisher's r to z transformation, computing the values, and then back tranforming the values using fisher's z to r transofrmation. } \usage{ describe.r(x, na.rm = TRUE, tr = 0.2, type = 3) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ A vector, matrix, or data.frame object of correlation coefficients. } \item{na.rm}{ A logical indicating whether NA values should be removed before calculations are done. } \item{tr}{ A numeric element between .00 and .50 specifying the amount of trimming to be done for the calculation of the trimmed mean. } \item{type}{ Which estimate of kurtosis should be used? See the describe function in the 'psych' package. } } \details{ The psych package function describe computes a number of descriptive statistics for ordinary data. However, correlation coefficients are typically r-to-z transformed before computing such statistics. This function makes getting the descriptive statistics for correlation coefficients easy by doing such transformations. } \value{ A data.frame of descriptive statistics: item name, item number, number of valid cases, mean, standard deviation, median, trimmed mean, mad: median absolute deviation (from the median), minimum, maximum, skew, kurtosis, standard error. } \author{ <NAME> } \seealso{ \code{\link[psych]{describe}} } \examples{ data(caq) data(acq.comp) mycors <- Profile.r(caq, acq.comp) # Get profile agreement correlations describe.r(mycors) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ descriptive statistics } \keyword{ correlations }% __ONLY ONE__ keyword per line <file_sep>/man/caq.items.Rd \name{caq.items} \alias{caq.items} \docType{data} \title{ CAQ Items } \description{ This is the item content from the California Adult Q-Sort (Block, 1961), a 100 item personality measure. } \usage{data(caq.items)} \format{ A data frame with content from 100 CAQ items. \describe{ \item{items}{ {CAQ001 - Critical, skeptical, not easily impressed} {\cr CAQ002 - A genuinely dependable and responsible person} {\cr CAQ003 - Has a wide range of interests} {\cr CAQ004 - Talkative} {\cr CAQ005 - Behaves in a giving way toward others} {\cr CAQ006 - Fastidious, perfectionistic} {\cr CAQ007 - Favors conservative values} {\cr CAQ008 - Appears to have a high degree of intellectual capacity} {\cr CAQ009 - Uncomfortable with uncertainty and complexity} {\cr CAQ010 - Anxiety and tension find outlet in bodily symptoms} {\cr CAQ011 - Protective of those close to him or her} {\cr CAQ012 - Tends to be self-defensive} {\cr CAQ013 - Thin-skinned; sensitive to criticism or interpersonal slight} {\cr CAQ014 - Genuinely submissive; accepts domination comfortably} {\cr CAQ015 - Skilled in social techniques of imaginative play, pretending, and humor} {\cr CAQ016 - Introspective and concerned with self as an object} {\cr CAQ017 - Sympathetic and considerate} {\cr CAQ018 - Initiates humor} {\cr CAQ019 - Seeks reassurance from others} {\cr CAQ020 - Has a rapid personal tempo; behaves and acts quickly} {\cr CAQ021 - Arouses nurturant feelings in others} {\cr CAQ022 - Feels a lack of personal meaning in life} {\cr CAQ023 - Extrapunitive; tends to transfer or project blame} {\cr CAQ024 - Prides self on being objective,rational} {\cr CAQ025 - Tends toward over-control of needs and impulses} {\cr CAQ026 - Productive; gets things done} {\cr CAQ027 - Shows condescending behavior in relations with others} {\cr CAQ028 - Tends to arouse liking and acceptance } {\cr CAQ029 - Turned to for advice and reassurance} {\cr CAQ030 - Gives up and withdraws where possible in the face of frustration and adversity} {\cr CAQ031 - Regards self as physically attractive} {\cr CAQ032 - Aware of the impression made on others} {\cr CAQ033 - Calm, relaxed in manner} {\cr CAQ034 - Over-reactive to minor frustrations, irritable} {\cr CAQ035 - Has warmth; has the capacity for close relationships; compassionate} {\cr CAQ036 - Subtly negativistic; tends to undermine and obstruct } {\cr CAQ037 - Guileful and deceitful, manipulative, opportunistic} {\cr CAQ038 - Has hostility toward others} {\cr CAQ039 - Thinks and associates ideas in unusual ways; has unconventional thought processes} {\cr CAQ040 - Vulnerable to real or fancied threat, generally fearful} {\cr CAQ041 - Moralistic} {\cr CAQ042 - Reluctant to commit to any definite course of action; tends to delay or avoid action} {\cr CAQ043 - Facially and/or gesturally expressive} {\cr CAQ044 - Evaluates the motivation of others in interpreting situations} {\cr CAQ045 - Has a brittle ego-defense system; does not cope well under stress or strainr} {\cr CAQ046 - Engages in personal fantasy and daydreams} {\cr CAQ047 - Has a readiness to feel guilt} {\cr CAQ048 - Keeps people at a distance; avoids close interpersonal relationships} {\cr CAQ049 - Basically distrustful of people in general} {\cr CAQ050 - Unpredictable and changeable in behavior and attitudes} {\cr CAQ051 - Genuinely values intellectual and cognitive matters} {\cr CAQ052 - Behaves in an assertive fashion} {\cr CAQ053 - Unable to delay gratification} {\cr CAQ054 - Emphasizes being with others; gregarious} {\cr CAQ055 - Self-defeating} {\cr CAQ056 - Responds to humor} {\cr CAQ057 - Interesting, arresting person} {\cr CAQ058 - Enjoys sensuous experiences (touch, taste, smell, physical contact)} {\cr CAQ059 - Concerned with own body and adequacy of physiological functioning} {\cr CAQ060 - Has insight into own motives and behavior} {\cr CAQ061 - Creates and exploits dependency in people} {\cr CAQ062 - Tends to be rebellious and non-conforming} {\cr CAQ063 - Judges self and other in conventional terms} {\cr CAQ064 - Socially perceptive of a wide range of interpersonal cues} {\cr CAQ065 - Pushes and tries to stretch limits} {\cr CAQ066 - Enjoys esthetic impressions; is esthetically reactive} {\cr CAQ067 - Self-indulgent} {\cr CAQ068 - Basically anxious} {\cr CAQ069 - Sensitive to anything that can be construed as a demand} {\cr CAQ070 - Behaves in an ethically consistent manner} {\cr CAQ071 - Has high aspiration level for self} {\cr CAQ072 - Concerned with own adequacy as a person} {\cr CAQ073 - Tends to perceive many different contexts in sexual terms} {\cr CAQ074 - Subjectively unaware of self-concern; feels satisfied with self} {\cr CAQ075 - Has a clear-cut, internally consistent personality} {\cr CAQ076 - Projects feelings and motivations onto others} {\cr CAQ077 - Appears straightforward, forthright, candid in dealing with others} {\cr CAQ078 - Feels cheated and victimized by life; self-pitying} {\cr CAQ079 - Ruminates and has persistent, preoccupying thoughts} {\cr CAQ080 - Interested in members of the opposite sex} {\cr CAQ081 - Physically attractive; good-looking} {\cr CAQ082 - Has fluctuating moods} {\cr CAQ083 - Able to see to the heart of important problems} {\cr CAQ084 - Cheerful} {\cr CAQ085 - Emphasizes communication through action and non-verbal behavior} {\cr CAQ086 - Repressive and dissociative tendencies; denies unpleasant thoughts and conflicts} {\cr CAQ087 - Interprets basically simple and clear-cut situations in complicated and particularizing ways} {\cr CAQ088 - Personally charming} {\cr CAQ089 - Compares self to others} {\cr CAQ090 - Concerned with philosophical problems} {\cr CAQ091 - Power-oriented; values power in self and others} {\cr CAQ092 - Has social poise and presence; appears socially at ease} {\cr CAQ093 - Behaves in gender-appropriate masculine or feminine style and manner} {\cr CAQ094 - Expresses hostile feelings directly} {\cr CAQ095 - Tends to offer advice} {\cr CAQ096 - Values own independence and autonomy} {\cr CAQ097 - Emotionally bland; has flattened affect} {\cr CAQ098 - Verbally fluent; can express ideas well} {\cr CAQ099 - Self-dramatizing; histrionic} {\cr CAQ100 - Does not vary roles; relates to everyone in the same way} } } } \source{ \url{http://psy2.fau.edu/~shermanr/index.html} } \references{ <NAME>. (1961). The Q-Sort Method in Personality Assessment and Psychiatric Research. Springfield, IL: <NAME>. } \examples{ data(caq.items) caq.items } \keyword{datasets} <file_sep>/man/rand.test.Rd \name{rand.test} \alias{rand.test} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Randomization Test } \description{ Computes a randomization test for the number of significant correlations and the average absolute r between set1 and set2. } \usage{ rand.test(set1, set2, sims = 1000, crit = 0.95, graph = TRUE, seed = 2) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{set1}{ A data.frame containing the variable(s) to be correlated with set2. Can be a single vector, but must be converted to a data.frame. } \item{set2}{ A matrix or data.frame containing the variables to be correlated with set1. } \item{sims}{ A numeric indicating the number of randomizations to be conducted. } \item{crit}{ A numeric between 0.0 and 1.0 indicating the critical value at which you will reject the null hypothesis of no relation between set1 and set2. } \item{graph}{ A logical indicating whether graphical output should be returned. } \item{seed}{ A numeric specifying the random seed to be used. If set to FALSE, no seed is used. } } \details{ When correlating a single variable of interest or a set of variables with another set of other variables, one practical consideration is the number of correlations one would expect to find by chance and/or the average absolute r between the two sets of variables. Following Sherman and Funder (2009), this function empirically estimates the sampling distribution for the number of statistically significant correlations and the average absolute r. } \value{ A list containing... \item{AbsR}{ A vector containing the results for the average absolute r between set1 and set2. Includes the N (for complete cases), the observed average absolute r, the expected average absolute r under a null hypothesis, the standard error of the average absolute r, the p-value of the observed average absolute r, the 99.9 percent upper and lower bound confidence intervals for the p-value, and the critical value for the test to be statistically significant. } \item{Sig}{ A vector containing the results for the number of significant correlations between set and the set2. Includes the N (for complete cases), the observed number significant, the expected number significant under a null hypothesis, the standard error of the number significant, the p-value of the observed number significant, the 99.9 percent upper and lower bound confidence intervals for the p-value,and the critical value for the test to be statisttically significant. } } \references{ <NAME>., & <NAME>. (2009). Evaluating correlations in studies of personality and behavior: Beyond the number of significant findings to be expected by chance. Journal of Research in Personality, 43, 1053-1063. } \author{ <NAME>. Sherman } \seealso{ \code{\link{q.cor}}, ~~~ } \examples{ data(caq) data(beh.comp) head(caq) head(beh.comp) #Note: In practice 'sims'=1000 is a better baseline rand.test(caq,beh.comp,sims=100) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ randomization test} <file_sep>/man/temp.match.Rd \name{temp.match} \alias{temp.match} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Template Matching } \description{ Returns the pearson correlation for each row in y.set with a given numeric vector 'template' for both the overall (raw) scores in y.set and the distinctive scores in y.set after using linear regression to remove the mean profile in y.set. } \usage{ temp.match(template, y.set, nomiss = 1, distinct = FALSE) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{template}{ A numeric vector of length equal to the number of columns of y.set to be correlated with each row of y.set } \item{y.set}{ A data.frame or matrix of which rows are to be correlated with template } \item{nomiss}{ A numeric element between .00 and 1.00 specifying the proportion values in y.set required to be complete before NA is returned instead of the the correlation. The default of 1.00 means that any missing case returns a result of NA. } \item{distinct}{ A logical indicating whether distinctive profile correlations (agreement) between template and y.set should be computed. } } \details{ For each observational unit in y.set its correlation with template is returned. If the proportion of valid values for an observational unit is less than nomiss NA is returned for that observational unit. If the distinct option is set to TRUE, this function also returns the "distinctive" correlations to the template after statistically removing the mean profile in y.set from each profile in y.set. } \value{ If distinct = FALSE: Returns a vector or template match scores corresponding to each row in y. If distinct = TRUE: A list of length 2: \item{yNorm}{ A vector containing the normative (average) profile of y.set } \item{Matches}{ A data.frame containing the Overall and Distinctive template match scores } } \author{ <NAME> } \seealso{ \code{\link{Profile.r}} \code{\link{Profile.reg}} \code{\link{temp.resid}} \code{\link{temp.match.rep}} } \examples{ data(caq) data(opt.temp) # Template Matching # Sometimes we want to know how closely each Profile matches a theoretically # or empirically derived Profile (i.e., a template). # Here is the template for the optimally adjusted person in the CAQ. opt.temp temp.match(opt.temp, caq) # The overall template match scores temp.match(opt.temp, caq, distinct=TRUE) # Both overall and distinctive template match scores # The replicability (reliablity) of the template match scores can also be estimated temp.match.rep(opt.temp,caq) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ Template Matching } <file_sep>/man/ipsatize.Rd \name{ipsatize} \alias{ipsatize} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Ipsatize Data } \description{ Returns a data.frame after ipsatizing (standardizing the rows) } \usage{ ipsatize(set) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{set}{ \code{A data.frame to be ipsatized} } } \details{ In research it is frequently desired to standardize the rows of a data.frame rather than the columns. This function does just that. } \value{ Returns a data.frame of the same dimensions as 'set' that contains ipsatized values} \author{ <NAME> } \seealso{ \code{\link{reQ}} } \examples{ data(bfi.set) #Lets ipsatize (within-person standardize) the Big Five Inventory (BFI) head(bfi.set) ip.bfi.set <- ipsatize(bfi.set) head(ip.bfi.set) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ Ipsatize } \keyword{ Standardize }% __ONLY ONE__ keyword per line <file_sep>/man/multicon-package.Rd \name{multicon-package} \alias{multicon-package} \alias{multicon} \docType{package} \title{ Multivariate Constructs } \description{ This package contains functions for examining multivariate constructs (MCs). } \details{ \tabular{ll}{ Package: \tab multicon\cr Type: \tab Package\cr Version: \tab 1.6\cr Date: \tab 2011-1-29\cr License: \tab GPL-2\cr } MCs are, as the name implies, constructs that consist of many variables. For example, personality is not a single variable, but a constellation of many individual variables. This is problematic for traditional analyses which only examine the relationships between only 1 variable (or just a few variables) and some outcome of interest. Within-person analyses are often interested in MCs as well. This package contains functions for examining such multivariate constructs. } \author{ <NAME> \cr Maintainer: <NAME> <<EMAIL>> \cr Compiler: <NAME> <<EMAIL>> } \references{ <NAME>. (2012). Understanding the New Statistics: Effect Sizes, Confidence Intervals, and Meta-Analysis. New York: Routledge.\cr <NAME>., <NAME>., <NAME>. (2000). The Riverside Behavioral Q-sort: A tool for the description of social behavior. Journal of Personality, 68, 451-489.\cr <NAME>., <NAME>., & <NAME>. (2010). Personality as manifest in behavior: Direct behavioral observation using the revised Riverside Behavioral Q-sort (RBQ-3.0). In <NAME>, <NAME>, <NAME>., Graziano, & <NAME> (Eds.), Then a miracle occurs: Focusing on beahvior in social psychological theory and research. (pp. 186-204). Oxford University Press.\cr <NAME>. (2008). A framework for Profile similarity: Integrating similarity, normativeness, and distinctiveness. Journal of Personality, 76(5), 1267-1316.\cr My website: \url{http://psy2.fau.edu/~shermanr/index.html} } \keyword{ multivariate constructs } \keyword{ replicability } \keyword{ personality psychology } \keyword{ within-person } \keyword{ profile analyses } \seealso{ \code{\link[psych]{psych}} } \examples{ # Some examples of the core functions in the multicon package: # Is personality related to behavior? This simple question becomes more # complex with the recognition that both personality and behavior are multivariate constructs. # One (of many) ways to quantify personality is with a a 100-item measure, # the California Adult Q-set (CAQ: Block, 1961). And one (of a few) ways to # quantify behavior is with a 67-item measure, the Riverside Behavioral Q-sort # (RBQ: Funder, Furr, & Colvin, Colvin, 2000; <NAME>, & Funder, 2010). # How well are these two instruments related? There are 100 * 67 = 6700 # possible correlations that could be examined one at a time. Alternatively, # we could answer our question more directly by simply seeing what the # (absolute) average correlation is amongst these two sets of items and testing # it against a baseline model that assumes zero association. The function # rand.test() does this. data(caq) data(v2rbq) # Note that in practice more sims (i.e., 1000 or more) might be preffered rand.test(caq, v2rbq, sims=100, graph=FALSE) # How is a specific single variable of interest (e.g., Extraversion) related # to some multivariate construct (e.g., behavior - as measured by the RBQ)? # Do the relationships differ by sex? The function q.cor() is # designed to answer this question. data(RSPdata) # Note that in practice more sims (i.e., 1000 or more) might be preffered myobj <- q.cor(RSPdata$sEXT, v2rbq, sex = RSPdata$ssex, fem = 1, male = 2, sims=100) myobj # The results can be organized by using q.cor.print() for easier interpretation data(rbqv3.items) q.cor.print(myobj, rbqv3.items, "RBQ", short=TRUE) # How well do two judgments of a target's personality agree with each other? # Again, assuming personality is measured as a multivariate construct # (e.g., the 100-item CAQ), this question is not so straightforward. One way # is to correlate the two judge's ratings across the 100-item pairs (profile correlation). # This can be done for each target with two judges. The function Profile.r() does this. data(acq1) # The first friend of a target being judged (N targets = 205) data(acq2) # The second friend of a target being judged Profile.r(acq1, acq2) # The agreements (correlations) for each target # Get summary statistics for the agreements describe.r(Profile.r(acq1, acq2)) # If we want to control for normativeness (see Furr, 2008) and get # significance tests (for both overall and distinctive agreement) we # can simply set distinct=TRUE. Profile.r(acq1, acq2, distinct=TRUE) # If we want to know how replicable (reliable) the agreement correaltions are # we can use Profile.r.rep() Profile.r.rep(acq1, acq2) # The package also includes some graphing functions for comparing group means # based on "The New Statistics" (Cumming, 2012). y <- c(rnorm(30), rnorm(30, mean=1)) group <- rep(1:2, each=30) catseye(y, group, las=1, main="A Catseye Plot", xlab="", grp.names=c("Control", "Experimental"), ylab="DV") catseye(y, group, las=1, main="A Catseye Plot #2", xlab="", grp.names=c("Control", "Experimental"), ylab="DV", conf=.80, col="cyan") df=data.frame(group=group,y=y) diffPlot(y ~ group,data=df,grp.names=c("Control", "Experimental"), xlab="", ylab="DV", main="A Difference Plot", sub="Arms are 95 percent CIs") } <file_sep>/man/acq2.Rd \name{acq2} \alias{acq2} \docType{data} \title{ Aquaintance (Number 2) CAQ ratings } \description{ This is an aquaintance rating of a participant's personality in the Riverside Situation Project. } \usage{data(acq2)} \format{ A data frame with 205 observations on the following 100 variables. \describe{ \item{\code{acq2CAQ001}}{Critical, skeptical, not easily impressed} \item{\code{acq2CAQ002}}{A genuinely dependable and responsible person} \item{\code{acq2CAQ003}}{Has a wide range of interests} \item{\code{acq2CAQ004}}{Talkative} \item{\code{acq2CAQ005}}{Behaves in a giving way toward others} \item{\code{acq2CAQ006}}{Fastidious, perfectionistic} \item{\code{acq2CAQ007}}{Favors conservative values} \item{\code{acq2CAQ008}}{Appears to have a high degree of intellectual capacity} \item{\code{acq2CAQ009}}{Uncomfortable with uncertainty and complexity} \item{\code{acq2CAQ010}}{Anxiety and tension find outlet in bodily symptoms} \item{\code{acq2CAQ011}}{Protective of those close to him or her} \item{\code{acq2CAQ012}}{Tends to be self-defensive} \item{\code{acq2CAQ013}}{Thin-skinned; sensitive to criticism or interpersonal slight} \item{\code{acq2CAQ014}}{Genuinely submissive; accepts domination comfortably} \item{\code{acq2CAQ015}}{Skilled in social techniques of imaginative play, pretending, and humor} \item{\code{acq2CAQ016}}{Introspective and concerned with self as an object} \item{\code{acq2CAQ017}}{Sympathetic and considerate} \item{\code{acq2CAQ018}}{Initiates humor} \item{\code{acq2CAQ019}}{Seeks reassurance from others} \item{\code{acq2CAQ020}}{Has a rapid personal tempo; behaves and acts quickly} \item{\code{acq2CAQ021}}{Arouses nurturant feelings in others} \item{\code{acq2CAQ022}}{Feels a lack of personal meaning in life} \item{\code{acq2CAQ023}}{Extrapunitive; tends to transfer or project blame} \item{\code{acq2CAQ024}}{Prides self on being objective,rational} \item{\code{acq2CAQ025}}{Tends toward over-control of needs and impulses} \item{\code{acq2CAQ026}}{Productive; gets things done} \item{\code{acq2CAQ027}}{Shows condescending behavior in relations with others} \item{\code{acq2CAQ028}}{Tends to arouse liking and acceptance } \item{\code{acq2CAQ029}}{Turned to for advice and reassurance} \item{\code{acq2CAQ030}}{Gives up and withdraws where possible in the face of frustration and adversity} \item{\code{acq2CAQ031}}{Regards self as physically attractive} \item{\code{acq2CAQ032}}{Aware of the impression made on others} \item{\code{acq2CAQ033}}{Calm, relaxed in manner} \item{\code{acq2CAQ034}}{Over-reactive to minor frustrations, irritable} \item{\code{acq2CAQ035}}{Has warmth; has the capacity for close relationships; compassionate} \item{\code{acq2CAQ036}}{Subtly negativistic; tends to undermine and obstruct } \item{\code{acq2CAQ037}}{Guileful and deceitful, manipulative, opportunistic} \item{\code{acq2CAQ038}}{Has hostility toward others} \item{\code{acq2CAQ039}}{Thinks and associates ideas in unusual ways; has unconventional thought processes} \item{\code{acq2CAQ040}}{Vulnerable to real or fancied threat, generally fearful} \item{\code{acq2CAQ041}}{Moralistic} \item{\code{acq2CAQ042}}{Reluctant to commit to any definite course of action; tends to delay or avoid action} \item{\code{acq2CAQ043}}{Facially and/or gesturally expressive} \item{\code{acq2CAQ044}}{Evaluates the motivation of others in interpreting situations} \item{\code{acq2CAQ045}}{Has a brittle ego-defense system; does not cope well under stress or strainr} \item{\code{acq2CAQ046}}{Engages in personal fantasy and daydreams} \item{\code{acq2CAQ047}}{Has a readiness to feel guilt} \item{\code{acq2CAQ048}}{Keeps people at a distance; avoids close interpersonal relationships} \item{\code{acq2CAQ049}}{Basically distrustful of people in general} \item{\code{acq2CAQ050}}{Unpredictable and changeable in behavior and attitudes} \item{\code{acq2CAQ051}}{Genuinely values intellectual and cognitive matters} \item{\code{acq2CAQ052}}{Behaves in an assertive fashion} \item{\code{acq2CAQ053}}{Unable to delay gratification} \item{\code{acq2CAQ054}}{Emphasizes being with others; gregarious} \item{\code{acq2CAQ055}}{Self-defeating} \item{\code{acq2CAQ056}}{Responds to humor} \item{\code{acq2CAQ057}}{Interesting, arresting person} \item{\code{acq2CAQ058}}{Enjoys sensuous experiences (touch, taste, smell, physical contact)} \item{\code{acq2CAQ059}}{Concerned with own body and adequacy of physiological functioning} \item{\code{acq2CAQ060}}{Has insight into own motives and behavior} \item{\code{acq2CAQ061}}{Creates and exploits dependency in people} \item{\code{acq2CAQ062}}{Tends to be rebellious and non-conforming} \item{\code{acq2CAQ063}}{Judges self and other in conventional terms} \item{\code{acq2CAQ064}}{Socially perceptive of a wide range of interpersonal cues} \item{\code{acq2CAQ065}}{Pushes and tries to stretch limits} \item{\code{acq2CAQ066}}{Enjoys esthetic impressions; is esthetically reactive} \item{\code{acq2CAQ067}}{Self-indulgent} \item{\code{acq2CAQ068}}{Basically anxious} \item{\code{acq2CAQ069}}{Sensitive to anything that can be construed as a demand} \item{\code{acq2CAQ070}}{Behaves in an ethically consistent manner} \item{\code{acq2CAQ071}}{Has high aspiration level for self} \item{\code{acq2CAQ072}}{Concerned with own adequacy as a person} \item{\code{acq2CAQ073}}{Tends to perceive many different contexts in sexual terms} \item{\code{acq2CAQ074}}{Subjectively unaware of self-concern; feels satisfied with self} \item{\code{acq2CAQ075}}{Has a clear-cut, internally consistent personality} \item{\code{acq2CAQ076}}{Projects feelings and motivations onto others} \item{\code{acq2CAQ077}}{Appears straightforward, forthright, candid in dealing with others} \item{\code{acq2CAQ078}}{Feels cheated and victimized by life; self-pitying} \item{\code{acq2CAQ079}}{Ruminates and has persistent, preoccupying thoughts} \item{\code{acq2CAQ080}}{Interested in members of the opposite sex} \item{\code{acq2CAQ081}}{Physically attractive; good-looking} \item{\code{acq2CAQ082}}{Has fluctuating moods} \item{\code{acq2CAQ083}}{Able to see to the heart of important problems} \item{\code{acq2CAQ084}}{Cheerful} \item{\code{acq2CAQ085}}{Emphasizes communication through action and non-verbal behavior} \item{\code{acq2CAQ086}}{Repressive and dissociative tendencies; denies unpleasant thoughts and conflicts} \item{\code{acq2CAQ087}}{Interprets basically simple and clear-cut situations in complicated and particularizing ways} \item{\code{acq2CAQ088}}{Personally charming} \item{\code{acq2CAQ089}}{Compares self to others} \item{\code{acq2CAQ090}}{Concerned with philosophical problems} \item{\code{acq2CAQ091}}{Power-oriented; values power in self and others} \item{\code{acq2CAQ092}}{Has social poise and presence; appears socially at ease} \item{\code{acq2CAQ093}}{Behaves in gender-appropriate masculine or feminine style and manner} \item{\code{acq2CAQ094}}{Expresses hostile feelings directly} \item{\code{acq2CAQ095}}{Tends to offer advice} \item{\code{acq2CAQ096}}{Values own independence and autonomy} \item{\code{acq2CAQ097}}{Emotionally bland; has flattened affect} \item{\code{acq2CAQ098}}{Verbally fluent; can express ideas well} \item{\code{acq2CAQ099}}{Self-dramatizing; histrionic} \item{\code{acq2CAQ100}}{Does not vary roles; relates to everyone in the same way} } } \details{ Subjects are listed as Rows (N=205). CAQ items (\code{\link{caq.items}}) (100 items) } \source{ \url{http://psy2.fau.edu/~shermanr/index.html} } \references{ <NAME>., <NAME>., & <NAME>. (2010). Situational similarity and personality predict behavioral consistency. Journal of Personality and Social Psychology, 99(2), 330-343 } \examples{ data(acq2) head(acq2) #aquaintance 2 } \keyword{datasets} <file_sep>/man/print.q.cor.rd \name{print.q.cor} \alias{print.q.cor} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Print q.cor object } \description{ Prints the results of a q.cor object in a more interpretable fashion. Also includes a convenient export option. } \usage{\method{print}{q.cor}(x, var.content = NULL, initial = NULL, rnd = 2, EXPORT = FALSE, short = FALSE, ...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ An object returned by the q.cor() function. } \item{var.content}{ An optional vector containing the content of the items or variables used as the "set" in a q.cor analysis. If left NULL default content is created. } \item{initial}{ An optional character element indicating the initial letters for the item codes or names in set. If left NULL "i" is used. } \item{rnd}{ A numeric element specifying the number of places to round each correlation coefficient. } \item{EXPORT}{ A file location to export the print results. If FALSE (default) no exportation is done. } \item{short}{ A logical indicating whether long output (default) or short output is to be returned. } \item{...}{ More arguments to pass to the print function. } } \details{ A print function for the \code{\link{q.cor}} function used to summarize the results of a q.cor object. This function easily adds the content of the items to the correlation table, sorts the correlation table, and allows the user to limit the table to only those items that are statistically significant at the p < .10 for the combined or .05 level for each gender by setting the short option = TRUE. In addition, the export option allows the user to output the results (either long or short) into a .csv file. } \author{ <NAME> } \seealso{ \code{\link{q.cor}} } \examples{ data(rbqv3.items) data(RSPdata) data(v2rbq) names(v2rbq) q.obj <- q.cor(RSPdata$sEXT, v2rbq, sex = RSPdata$ssex, fem = 1, male = 2, sims = 1000) #It might be necessary to adjust size of the width of your console to make this content fit. print(q.obj) # Accepting only the default arguments # Taking advantage of the other arguments print(q.obj, var.content = rbqv3.items, initial = "RBQ", short = TRUE, EXPORT = FALSE) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ q.cor } \keyword{ print }% __ONLY ONE__ keyword per line <file_sep>/man/Profile.ICC.Rd \name{Profile.ICC} \alias{Profile.ICC} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Profile Intra-class Correlation } \description{ Calculates the Profile intra-class correlations for a single profile (row) and a composite of the profiles (rows), following Shrout and Fleiss (1979), for the corresponding rows in each set provided to the function. ICC1: Each target is rated by a different judge and the judges are selected at random. (This is a one-way ANOVA fixed effects model and is found by (MSB- MSW)/(MSB+ (nr-1)*MSW)) ICC2: A random sample of k judges rate each target. The measure is one of absolute agreement in the ratings. Found as (MSB- MSE)/(MSB + (nr-1)*MSE + nr*(MSJ-MSE)/nc) ICC3: A fixed set of k judges rate each target. There is no generalization to a larger population of judges. (MSB - MSE)/(MSB+ (nr-1)*MSE) Then, for each of these cases, is reliability to be estimated for a single rating or for the average of k ratings? (The 1 rating case is equivalent to the average intercorrelation, the k rating case to the Spearman Brown adjusted reliability.) ICC1 is sensitive to differences in means between raters and is a measure of absolute agreement. ICC2 and ICC3 remove mean differences between judges, but are sensitive to interactions of raters by judges. The difference between ICC2 and ICC3 is whether raters are seen as fixed or random effects. ICC1k, ICC2k, ICC3K reflect the means of k raters. } \usage{ Profile.ICC(set1, set2, ..., omit = TRUE) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{set1}{ A data.frame or matrix with corresponding rows in set2 and any additional sets passed to the function. } \item{set2}{ A data.frame or matrix with correpsonding rows in set1 and any additional sets passed to the function. } \item{\dots}{ Additional matrices or data.frames with corresponding rows to set1 and set2 passed to the function. } \item{omit}{ A logical indicating whether incomplete cases should be omitted from analysis. If set to FALSE and data are missing, warning(s) will result. } } \details{ This function returns the ICCs for the corresponding rows from set1, set2, and each additional set to passed to the function where single Profile ICCs (ICC[x,1]) and composite ICCs (ICC[x,k]) are computed for each group of corresponding rows in the sets. Follow Shrout and Fleiss (1979) for interpretation of the different ICCs. } \value{ A data.frame containing the above described ICCs. } \references{ <NAME>. & <NAME>. (1979). Intraclass correlations: Uses in assessing rater reliability. Psychological Bulletin, 86, 420-428 } \author{ <NAME> } \seealso{ \code{\link{get.ICC}} \code{\link{item.ICC}} } \examples{ data(acq1) data(acq2) #lets look at the Profile ICC between two aquaintance ratings of subjects' personality names(acq1) names(acq2) Profile.ICC(acq1, acq2) #We can get the descriptives for these using describe() from the 'psych' package describe(Profile.ICC(acq1, acq2)) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ intraclass correlation } \keyword{ profile similarity } \keyword{ agreement } <file_sep>/man/aov1way.Rd \name{aov1way} \alias{aov1way} %- Also NEED an '\alias' for EACH other topic documented here. \title{ One Way Anova } \description{ Returns the results of a one-way ANOVA on a matrix in x } \usage{ aov1way(x) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ A matrix with each column corresponding to a different level of the IV } } \details{ Similar to the R function aov only this returns the effect size eta for the between-S effect } \value{ A matrix displaying the ANOVA summary table. } \author{ <NAME> } \examples{ T1=rnorm(10,mean=1,sd=.5) T2=rnorm(10,mean=1.1,sd=.45) T3=rnorm(10,mean=1.2,sd=.4) DVxIV=cbind(T1,T2,T3) aov1way(DVxIV) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ anova } \keyword{ one-way }% __ONLY ONE__ keyword per line <file_sep>/man/v4rbq.Rd \name{v4rbq} \alias{v4rbq} \docType{data} \title{ Situation 3 RBQ } \description{ This is participants' self-ratings of their own behavior using the RBQ in the 3rd of 4 situations that they experienced. } \usage{data(v4rbq)} \format{ A data frame with 205 observations on the following 67 variables. \describe{ \item{\code{v4rbq001}}{Interviews others (if present) (e.g., asks a series of questions)} \item{\code{v4rbq002}}{Volunteers a large amount of information about self} \item{\code{v4rbq003}}{Seems interested in what someone had to say (Disregard whether interest appears "genuine" or "polite")} \item{\code{v4rbq004}}{Tries to control the situation (Disregard whether attempts at control succeed or not)} \item{\code{v4rbq005}}{Dominates the situation (Disregard intention, e.g., if P dominates the situation "by default" because other(s) present do very little, this item should receive high placement)} \item{\code{v4rbq006}}{Appears to be relaxed and comfortable} \item{\code{v4rbq007}}{Exhibits social skills (e.g., does things to make other(s) comfortable, keeps conversation moving, entertains or charms other(s))} \item{\code{v4rbq008}}{Is reserved and unexpressive (e.g., expresses little affect; acts in a stiff, formal manner)} \item{\code{v4rbq009}}{Laughs frequently (Disregard whether laughter appears to be "nervous" or "genuine")} \item{\code{v4rbq010}}{Smiles frequently} \item{\code{v4rbq011}}{Is physically animated; moves around a great deal} \item{\code{v4rbq012}}{Seems to like other(s) present (e.g., would probably like to be friends with them)} \item{\code{v4rbq013}}{Exhibits an awkward interpersonal style (e.g., seems to have difficulty knowing what to say, mumbles, fails to respond to other(s)' conversational advances)} \item{\code{v4rbq014}}{Compares self to other(s) (whether others are present or not)} \item{\code{v4rbq015}}{Shows high enthusiasm and a high energy level} \item{\code{v4rbq016}}{Shows a wide range of interests (e.g., talks about many topics)} \item{\code{v4rbq017}}{Talks at rather than with other(s) (e.g., conducts a monologue, ignores what others say)} \item{\code{v4rbq018}}{Expresses agreement frequently (High placement implies agreement is expressed unusually often, e.g., in response to each and every statement made. Low placement implies unusual lack of expression of agreement.)} \item{\code{v4rbq019}}{Expresses criticism (of anybody or anything) (Low placement implies expresses praise)} \item{\code{v4rbq020}}{Is talkative (as observed in this situation)} \item{\code{v4rbq021}}{Expresses insecurity (e.g., seems touchy or overly sensitive)} \item{\code{v4rbq022}}{Shows physical signs of tension or anxiety (e.g., fidgets nervously, voice wavers)(Lack of signs of anxiety = middle placement; low placement = lack of signs under circumstances where you would expect to see them)} \item{\code{v4rbq023}}{Exhibits a high degree of intelligence (NB: At issue is what is displayed in the interaction not what may or may not be latent. Thus, give this item high placement only if P actually says or does something of high intelligence. Low placement implies exhibition of low intelligence; medium placement = no information one way or the other)} \item{\code{v4rbq024}}{Expresses sympathy (to anyone, i.e., including conversational references)(Low placement implies unusual lack of sympathy)} \item{\code{v4rbq025}}{Initiates humor} \item{\code{v4rbq026}}{Seeks reassurance (e.g., asks for agreement, fishes for praise)} \item{\code{v4rbq027}}{Exhibits condescending behavior (e.g., acts as if self is superior to others [present, or otherwise])(Low placement implies acting inferior)} \item{\code{v4rbq028}}{Seems likable (to other(s) present)} \item{\code{v4rbq029}}{Seeks advice} \item{\code{v4rbq030}}{Appears to regard self as physically attractive} \item{\code{v4rbq031}}{Acts irritated} \item{\code{v4rbq032}}{Expresses warmth (to anyone, e.g., include any references to "my close friend," etc)} \item{\code{v4rbq033}}{Tries to undermine, sabotage or obstruct} \item{\code{v4rbq034}}{Expresses hostility (no matter toward whom or what)} \item{\code{v4rbq035}}{Is unusual or unconventional in appearance} \item{\code{v4rbq036}}{Behaves in a fearful or timid manner} \item{\code{v4rbq037}}{Is expressive in face, voice or gestures} \item{\code{v4rbq038}}{Expresses interest in fantasy or daydreams (Low placement only if such interest is explicitly disavowed)} \item{\code{v4rbq039}}{Expresses guilt (about anything)} \item{\code{v4rbq040}}{Keep other(s) at a distance; avoids development of any sort of interpersonal relationship (Low placement implies behavior to get close to other(s))} \item{\code{v4rbq041}}{Shows interest in intellectual or cognitive matters (e.g., by discussing an intellectual idea in detail or with enthusiasm)} \item{\code{v4rbq042}}{Seems to enjoy the situation} \item{\code{v4rbq043}}{Says or does something interesting} \item{\code{v4rbq044}}{Says negative things about self (e.g., is self-critical; expresses feelings of inadequacy)} \item{\code{v4rbq045}}{Displays ambition (e.g., passionate discussion of career plans, course grades, opportunities to make money)} \item{\code{v4rbq046}}{Blames others (for anything)} \item{\code{v4rbq047}}{Expresses self-pity or feelings of victimization} \item{\code{v4rbq048}}{Expresses sexual interest (e.g., acts attracted to someone present; expresses interest in dating or sexual matters in general)} \item{\code{v4rbq049}}{Behaves in a cheerful manner} \item{\code{v4rbq050}}{Gives up when faced with obstacles (Low placement implies unusual persistence)} \item{\code{v4rbq051}}{Behaves in a stereotypically masculine/feminine style or manner (Apply the usual stereotypes appropriate to the P's sex. Low placement implies behavior stereotypical of the opposite sex)} \item{\code{v4rbq052}}{Offers advice} \item{\code{v4rbq053}}{Speaks fluently and expresses ideas well} \item{\code{v4rbq054}}{Emphasizes accomplishments of self, family or acquaintances (Low placement = emphasizes failures of these individuals)} \item{\code{v4rbq055}}{Behaves in a competitive manner (Low placement implies cooperative behavior)} \item{\code{v4rbq056}}{Speaks in a loud voice} \item{\code{v4rbq057}}{Speaks sarcastically (e.g., says things (s)he does not mean; makes facetious comments that are not necessarily funny)} \item{\code{v4rbq058}}{Makes or approaches physical contact with other(s) (Of any sort, including sitting unusually close without touching) (Low placement implies unusual avoidance of physical contact, such as large interpersonal distance)} \item{\code{v4rbq059}}{Engages in constant eye contact with someone (Low placement implies unusual lack of eye contact)} \item{\code{v4rbq060}}{Seems detached from the situation} \item{\code{v4rbq061}}{Speaks quickly (Low placement = speaks slowly)} \item{\code{v4rbq062}}{Acts playful} \item{\code{v4rbq063}}{Other(s) seek advice from P} \item{\code{v4rbq064}}{Concentrates on/works hard at a task (Low placement implies loafing)} \item{\code{v4rbq065}}{Engages in physical activity (e.g., works up a sweat)(Low placement = almost completely sedentary)} \item{\code{v4rbq066}}{Acts in a self-indulgent manner (e.g., spending, eating, or drinking)(Low placement implies self-denial)} \item{\code{v4rbq067}}{Exhibits physical discomfort or pain (High placement = in excess of what seems proportionate; Low placement implies lack of these signs where expected)} } } \details{ Subjects are listed as Rows (N=205). RBQ items (\code{\link{rbqv3.items}}) (100 items) } \source{ \url{http://psy2.fau.edu/~shermanr/index.html} } \references{ <NAME>., <NAME>., & <NAME>. (2010). Situational similarity and personality predict behavioral consistency. Journal of Personality and Social Psychology, 99(2), 330-343 } \examples{ data(v4rbq) head(v4rbq) data(rbqv3.items)#lets look at the RBQ items rbqv3.items } \keyword{datasets} <file_sep>/man/tContrast.Rd \name{tContrast} \alias{tContrast} \alias{tContrast.default} \alias{tContrast.formula} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Constrast T-tests } \description{ Computes a t-test for multiple groups using a given set of contrast weights. } \usage{ tContrast(IV, ...) ## Default Method \method{tContrast}{default}(IV, DV, wgt = c(1, -1), alpha = .05, EQVAR = FALSE, alternative = "unequal", ...) ## Method for class 'formula' \method{tContrast}{formula}(formula, data = NULL, wgt = c(1, -1), alpha = .05, EQVAR = FALSE, alternative = "unequal", ...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{IV}{ A factor of the same length as DV containing the independent variable codes. } \item{DV}{ A numeric vector of the same length as IV containing the measured values. } \item{formula}{ A formula of the form lhs ~ rhs where lhs is a numeric vector containing the data values and rhs is a variable containing the corresponding groups. } \item{data}{ An optional data frame containing the variables in the formula. } \item{wgt}{ A numeric vector containing the contrast weights corresponding to each successive level of the IV. Defaults to c(1, -1), implying that the first group is expected to have a higher mean than the second. } \item{alpha}{ A numeric element > .00 and < 1.00 specifying the Type I error rate. } \item{EQVAR}{ A logical indicating whether equal variances amongst the groups should be assumed. Defaults to FALSE (Welch's Method). } \item{alternative}{ A character vector specifying the alternative hypothesis. Must be one of "unequal", "greater", or "less". } \item{...}{ Further arguments to be passed to or from methods. } } \details{ This function computes a t-contrast for any number of groups based on the specificed constrast weights (Rosenthal, Rosnow, & Rubin, 2000). By setting the EQVAR option to TRUE degrees of freedom are consistent with Student's method. If EQVAR is FALSE (default) then degrees of freedom are calculated using the Welch-Sattertwaite approximation. The wgt option allows one to specify contrast weights to test hypotheses with more than 2 levels of an IV. By default it tests the hypothesis that two means are unequal. If a directional hypothesis is known ahead of time, use "greater" to predict that higher contrast weights have higher means and "less" to predict the opposite. For a robust version of this function see \code{\link{yuenContrast}}. The entire family of possible T-test equations can be found here: http://rynesherman.com/T-Family.doc } \value{A list containing... \item{Ms}{A data.frame with the sample size, mean, and weight for each group.} \item{test}{A data.frame with the test statistic (stat), the degrees of freedom (df), the critical value for the test statistic (crit), the p-value, and an r-contrast (effect size).} } \references{ <NAME>., <NAME>., & <NAME>. (2000). Contrasts and Effect Sizes in Behavioral Research: A Correlational Approach. Cambridge, UK: Cambridge University Press. } \author{ <NAME> } \seealso{ \code{\link{yuenContrast}} \code{\link{t.test}} } \examples{ dv <- c(rnorm(30, mean=1, sd=2), rnorm(20)) iv <- c(rep(1,30),rep(2,20)) # Student's t-test (assuming equal variances) t.test(dv ~ iv, var.equal=TRUE) # Welch's t-test (not assuming equal variance) t.test(dv ~ iv, var.equal=FALSE) # tContrast assuming equal variances tContrast(iv, dv, EQVAR=TRUE) # tContrast not assuming equal variances tContrast(iv, dv, EQVAR=FALSE) # Contrast with 3 Groups dv <- c(rnorm(30), rnorm(20, mean=-.5), rnorm(10, mean=-1)) iv <- c(rep("c",30), rep("b", 20), rep("a", 10)) # t-contrast with Welch-Sattertwaite DFs tContrast(iv, dv, wgt=c(1, 0, -1)) # Compare with yuenContrast with no trimming yuenContrast(iv, dv, wgt=c(1, 0, -1), tr=0) # With the formula method yuenContrast(dv ~ iv, wgt = c(1, 0, -1)) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ t test } \keyword{ contrast } % __ONLY ONE__ keyword per line <file_sep>/man/RSPdata.Rd \name{RSPdata} \alias{RSPdata} \docType{data} \title{ Riverside Situation Project Data } \description{ This is the original data file for the \code{\link{multicon-package}}. All other data objects are subsetted or dervived from this dataset. This data set is part of a larger data collection project, the Riverside Situation Project (RSP). The Riverside Situation Project was designed to measure and understand the psychological characteristics of situations and their relationship to personality, behavior, and emotion. The details of the data collection are provided by Sherman and colleagues (2010), but are briefly summarized here. 205 target participants came to the lab on 5 occastions. On the first visit to the lab participants completed a large number of personality measures about themselves. They also provided the names to of two acquaintances who knew them well and could come to the lab to rate their (the participants) personalities. On visits 2-5, participants came to the lab and were asked to describe the situation they were in the day before at a prespecified time. They then rated that situation using the Riverside Situational Q-sort, a measure of psychological characteristics of situations. Lastly, participants rated their behavior in that situation using the Riverside Behavioral Q-sort. Each visit was separated by a minimum of 48 hours. Data from that project have been used in several publications (<NAME>, & Fundeer, 2010, 2012, 2013; <NAME>, & Funder, 2013). } \usage{data(RSPdata)} \format{ A data frame with 205 observations on 619 variables. The following items are only contained in RSPdata: SID: Subject ID Number \cr ssex: Subject sex: male = 1, fem = 2 \cr sEXT: Extraversion Composite from the BFI \cr sAGR: Agreeableness Composite from the BFI \cr sCON: Conscientiousness Composite from the BFI \cr sNEUR Neuroticism Compostie from the BFI \cr sOPEN: Openness Composite from the BFI RSPdata also contains items from the following datasets: \link{acq1}: This is an aquaintance rating of a participant's personality in the Riverside Situation Project. \cr \link{acq2}: This is an aquaintance rating of a participant's personality in the Riverside Situation Project. \cr \link{acq.comp}: This is the composite of two aquaintace CAQ ratings of a participant's personality from the Riverside Situation Project \cr \link{bfi.set}: These are Big Five Inventory self ratings of participants from the Riverside Situation Project. \cr \link{caq}: These are self ratings of personality using the California Adult Q-Set in the Riverside Situation Project. \cr \link{v2rbq}: This is participants' self-ratings of their own behavior using the RBQ in the 1st of 4 situations that they experienced. \cr \link{v3rbq}: This is participants' self-ratings of their own behavior using the RBQ in the 2nd of 4 situations that they experienced. \cr \link{v4rbq}: This is participants' self-ratings of their own behavior using the RBQ in the 3rd of 4 situations that they experienced. \cr \link{v5rbq}: This is participants' self-ratings of their own behavior using the RBQ in the 4th of 4 situations that they experienced. \cr \link{beh.comp}: This is a composite of a participants' behavior across 4 situations. } \details{ Subjects are listed as Rows (N=205). Items of several presonality measures (e.g. CAQ, BFI) and measures of behavior (RBQ) are listed in columns. } \source{ \url{http://psy2.fau.edu/~shermanr/index.html} \url{http://rap.ucr.edu/furrwagermanfunder.doc} } \references{ <NAME>., <NAME>., & <NAME>. (2010). Situational similarity and personality predict behavioral consistency. Journal of Personality and Social Psychology, 99(2), 330-343.\cr <NAME>., <NAME>., & <NAME>. (2012). Properties of persons and situations related to overall and distinctive personality-behavior congruence. Journal of Research in Personality, 46, 87-101.\cr <NAME>., <NAME>., & <NAME>. (2013). Situational construal is related to personality and gender. Journal of Research in Personality, 47(1), 142-154.\cr <NAME>., <NAME>., & <NAME>. (2013). The behavioral correlates of overall and distinctive life history strategy. Journal of Personality and Social Psychology, 105(5), 873-888. } \examples{ data(RSPdata) names(RSPdata) str(RSPdata) } \keyword{datasets} <file_sep>/man/lin.coef.Rd \name{lin.coef} \alias{lin.coef} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Linear Coefficients } \description{ Returns the slope and intercept for x predicting y } \usage{ lin.coef(x, y, out = "both", nomiss = 0.8) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ A numeric vector of the same length as y } \item{y}{ A numeric vector of the same length as x } \item{out}{ A character vector specifying whether the result should return just the intercept ("int"), just the slope ("slope") or both ("both") which defaults to "both" } \item{nomiss}{ A numeric between .00 and 1.00 specifying the proportion of x-y pairs required to be complete before NA is returned instead of the regression coefficients. The default of .80 means that if more than 20 percent of the x-y pairs are incomplete an NA will be returned. } } \details{ This function is largely designed to increase computation efficiency for getting regression coefficients. For instance, this function is called by the Profile.reg function (see Profile.reg). } \value{ \item{b0 }{intercept of the regression line from y predicted from x } \item{b1 }{slope of the regression line frome y predicted from x } } \author{ <NAME> } \seealso{ \code{\link{Profile.reg}} } \examples{ data(RSPdata) # Lets predict self reported extraversion from gender lin.coef(RSPdata$ssex,RSPdata$sEXT) # confirm that these numbers match the results from lm() lm(sEXT ~ ssex, data = RSPdata) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ linear regression } \keyword{ coefficients }% __ONLY ONE__ keyword per line <file_sep>/man/v2rbq.Rd \name{v2rbq} \alias{v2rbq} \docType{data} \title{ Situation 1 RBQ } \description{ This is participants' self-ratings of their own behavior using the RBQ in the 1st of 4 situations that they experienced. } \usage{data(v2rbq)} \format{ A data frame with 205 observations on the following 67 variables. \describe{ \item{\code{v2rbq001}}{Interviews others (if present) (e.g., asks a series of questions)} \item{\code{v2rbq002}}{Volunteers a large amount of information about self} \item{\code{v2rbq003}}{Seems interested in what someone had to say (Disregard whether interest appears "genuine" or "polite")} \item{\code{v2rbq004}}{Tries to control the situation (Disregard whether attempts at control succeed or not)} \item{\code{v2rbq005}}{Dominates the situation (Disregard intention, e.g., if P dominates the situation "by default" because other(s) present do very little, this item should receive high placement)} \item{\code{v2rbq006}}{Appears to be relaxed and comfortable} \item{\code{v2rbq007}}{Exhibits social skills (e.g., does things to make other(s) comfortable, keeps conversation moving, entertains or charms other(s))} \item{\code{v2rbq008}}{Is reserved and unexpressive (e.g., expresses little affect; acts in a stiff, formal manner)} \item{\code{v2rbq009}}{Laughs frequently (Disregard whether laughter appears to be "nervous" or "genuine")} \item{\code{v2rbq010}}{Smiles frequently} \item{\code{v2rbq011}}{Is physically animated; moves around a great deal} \item{\code{v2rbq012}}{Seems to like other(s) present (e.g., would probably like to be friends with them)} \item{\code{v2rbq013}}{Exhibits an awkward interpersonal style (e.g., seems to have difficulty knowing what to say, mumbles, fails to respond to other(s)' conversational advances)} \item{\code{v2rbq014}}{Compares self to other(s) (whether others are present or not)} \item{\code{v2rbq015}}{Shows high enthusiasm and a high energy level} \item{\code{v2rbq016}}{Shows a wide range of interests (e.g., talks about many topics)} \item{\code{v2rbq017}}{Talks at rather than with other(s) (e.g., conducts a monologue, ignores what others say)} \item{\code{v2rbq018}}{Expresses agreement frequently (High placement implies agreement is expressed unusually often, e.g., in response to each and every statement made. Low placement implies unusual lack of expression of agreement.)} \item{\code{v2rbq019}}{Expresses criticism (of anybody or anything) (Low placement implies expresses praise)} \item{\code{v2rbq020}}{Is talkative (as observed in this situation)} \item{\code{v2rbq021}}{Expresses insecurity (e.g., seems touchy or overly sensitive)} \item{\code{v2rbq022}}{Shows physical signs of tension or anxiety (e.g., fidgets nervously, voice wavers)(Lack of signs of anxiety = middle placement; low placement = lack of signs under circumstances where you would expect to see them)} \item{\code{v2rbq023}}{Exhibits a high degree of intelligence (NB: At issue is what is displayed in the interaction not what may or may not be latent. Thus, give this item high placement only if P actually says or does something of high intelligence. Low placement implies exhibition of low intelligence; medium placement = no information one way or the other)} \item{\code{v2rbq024}}{Expresses sympathy (to anyone, i.e., including conversational references)(Low placement implies unusual lack of sympathy)} \item{\code{v2rbq025}}{Initiates humor} \item{\code{v2rbq026}}{Seeks reassurance (e.g., asks for agreement, fishes for praise)} \item{\code{v2rbq027}}{Exhibits condescending behavior (e.g., acts as if self is superior to others [present, or otherwise])(Low placement implies acting inferior)} \item{\code{v2rbq028}}{Seems likable (to other(s) present)} \item{\code{v2rbq029}}{Seeks advice} \item{\code{v2rbq030}}{Appears to regard self as physically attractive} \item{\code{v2rbq031}}{Acts irritated} \item{\code{v2rbq032}}{Expresses warmth (to anyone, e.g., include any references to "my close friend," etc)} \item{\code{v2rbq033}}{Tries to undermine, sabotage or obstruct} \item{\code{v2rbq034}}{Expresses hostility (no matter toward whom or what)} \item{\code{v2rbq035}}{Is unusual or unconventional in appearance} \item{\code{v2rbq036}}{Behaves in a fearful or timid manner} \item{\code{v2rbq037}}{Is expressive in face, voice or gestures} \item{\code{v2rbq038}}{Expresses interest in fantasy or daydreams (Low placement only if such interest is explicitly disavowed)} \item{\code{v2rbq039}}{Expresses guilt (about anything)} \item{\code{v2rbq040}}{Keep other(s) at a distance; avoids development of any sort of interpersonal relationship (Low placement implies behavior to get close to other(s))} \item{\code{v2rbq041}}{Shows interest in intellectual or cognitive matters (e.g., by discussing an intellectual idea in detail or with enthusiasm)} \item{\code{v2rbq042}}{Seems to enjoy the situation} \item{\code{v2rbq043}}{Says or does something interesting} \item{\code{v2rbq044}}{Says negative things about self (e.g., is self-critical; expresses feelings of inadequacy)} \item{\code{v2rbq045}}{Displays ambition (e.g., passionate discussion of career plans, course grades, opportunities to make money)} \item{\code{v2rbq046}}{Blames others (for anything)} \item{\code{v2rbq047}}{Expresses self-pity or feelings of victimization} \item{\code{v2rbq048}}{Expresses sexual interest (e.g., acts attracted to someone present; expresses interest in dating or sexual matters in general)} \item{\code{v2rbq049}}{Behaves in a cheerful manner} \item{\code{v2rbq050}}{Gives up when faced with obstacles (Low placement implies unusual persistence)} \item{\code{v2rbq051}}{Behaves in a stereotypically masculine/feminine style or manner (Apply the usual stereotypes appropriate to the P's sex. Low placement implies behavior stereotypical of the opposite sex)} \item{\code{v2rbq052}}{Offers advice} \item{\code{v2rbq053}}{Speaks fluently and expresses ideas well} \item{\code{v2rbq054}}{Emphasizes accomplishments of self, family or acquaintances (Low placement = emphasizes failures of these individuals)} \item{\code{v2rbq055}}{Behaves in a competitive manner (Low placement implies cooperative behavior)} \item{\code{v2rbq056}}{Speaks in a loud voice} \item{\code{v2rbq057}}{Speaks sarcastically (e.g., says things (s)he does not mean; makes facetious comments that are not necessarily funny)} \item{\code{v2rbq058}}{Makes or approaches physical contact with other(s) (Of any sort, including sitting unusually close without touching) (Low placement implies unusual avoidance of physical contact, such as large interpersonal distance)} \item{\code{v2rbq059}}{Engages in constant eye contact with someone (Low placement implies unusual lack of eye contact)} \item{\code{v2rbq060}}{Seems detached from the situation} \item{\code{v2rbq061}}{Speaks quickly (Low placement = speaks slowly)} \item{\code{v2rbq062}}{Acts playful} \item{\code{v2rbq063}}{Other(s) seek advice from P} \item{\code{v2rbq064}}{Concentrates on/works hard at a task (Low placement implies loafing)} \item{\code{v2rbq065}}{Engages in physical activity (e.g., works up a sweat)(Low placement = almost completely sedentary)} \item{\code{v2rbq066}}{Acts in a self-indulgent manner (e.g., spending, eating, or drinking)(Low placement implies self-denial)} \item{\code{v2rbq067}}{Exhibits physical discomfort or pain (High placement = in excess of what seems proportionate; Low placement implies lack of these signs where expected)} } } \details{ Subjects are listed as Rows (N=205). RBQ items (\code{\link{rbqv3.items}}) (67 items) } \source{ \url{http://psy2.fau.edu/~shermanr/index.html} } \references{ <NAME>., <NAME>., & <NAME>. (2010). Situational similarity and personality predict behavioral consistency. Journal of Personality and Social Psychology, 99(2), 330-343 } \examples{ data(v2rbq) head(v2rbq) data(rbqv3.items)#lets look at the RBQ items rbqv3.items } \keyword{datasets}<file_sep>/man/opt.temp.Rd \name{opt.temp} \alias{opt.temp} \docType{data} \title{ Optimum Template } \description{ This is a CAQ Template for an optimally adjusted person } \usage{data(opt.temp)} \format{ Opt.temp contains scores from 1 to 9 on each of 100 \link{caq.items} for an optimally adjusted person. } \details{ A CAQ description of the Optimally Adjusted Person based on 9 independent clinician ratings. The average profile agreement amongst the ratings was r = .78, implying a spearman-brown reliability of .97. } \references{ <NAME>. (1961). The Q-Sort Method in Personality Assessment and Psychiatric Research. Springfield, IL: <NAME>. } \examples{ data(opt.temp) opt.temp } \keyword{datasets} <file_sep>/man/n4rci.Rd \name{n4rci} \alias{n4rci} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Sample Size for CI for r } \description{ 1) Calculates the width of a confidence interval for the correlation coefficient r given the sample size (N) and the alpha level. 2) Calculates the sample size required to obtain a confidence interaval for the correlation coefficient r of a desired width (CIwidth) given alpha. 3) Calculates the alpha for a confidence interval for r given desired confidence interval width (CIwidth) and the sample size (N). } \usage{ n4rci(CIwidth = NULL, N = NULL, alpha = NULL) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{CIwidth}{ A numeric between 0 and 1.00 indicating desired confidence interval width. } \item{N}{ A numeric element greater than 3 indicating the desired sample size. } \item{alpha}{ A numeric element between 0 and 1.00 indicating the desired alpha (Type-I error rate) level. } } \details{ Given two of the three arguments, calculates the result of the third. Is probably most useful for determining the sample size one needs to obtain a desired confidence interval. Note that when operated in this mode the result is not always a whole number (i.e., partial Ns are returned). Rounding up is recommended. Is second most useful for calculating the width of one's confidence interval given the sample size. Is third (least) useful for calculating alpha. } \value{ No matter which mode is used, the N, the CI Width and the alpha are returned. } \author{ <NAME> } \examples{ n4rci(CIwidth=.15, N=NULL, alpha=.05) #finding the necessary N n4rci(CIwidth=NULL, N=200, alpha=.05) #finding the CI width n4rci(CIwidth=.3, N=120, alpha=NULL) #finding the alpha } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ confidence intervals } \keyword{ power analysis } \keyword{ sample size }% __ONLY ONE__ keyword per line <file_sep>/man/caq.Rd \name{caq} \alias{caq} \docType{data} \title{ Californa Adult Q-Set } \description{ These are self ratings of personality using the California Adult Q-Set in the Riverside Situation Project. } \usage{data(caq)} \format{ A data frame with 205 observations on the following 100 variables. \describe{ \item{\code{sCAQ001}}{Critical, skeptical, not easily impressed} \item{\code{sCAQ002}}{A genuinely dependable and responsible person} \item{\code{sCAQ003}}{Has a wide range of interests} \item{\code{sCAQ004}}{Talkative} \item{\code{sCAQ005}}{Behaves in a giving way toward others} \item{\code{sCAQ006}}{Fastidious, perfectionistic} \item{\code{sCAQ007}}{Favors conservative values} \item{\code{sCAQ008}}{Appears to have a high degree of intellectual capacity} \item{\code{sCAQ009}}{Uncomfortable with uncertainty and complexity} \item{\code{sCAQ010}}{Anxiety and tension find outlet in bodily symptoms} \item{\code{sCAQ011}}{Protective of those close to him or her} \item{\code{sCAQ012}}{Tends to be self-defensive} \item{\code{sCAQ013}}{Thin-skinned; sensitive to criticism or interpersonal slight} \item{\code{sCAQ014}}{Genuinely submissive; accepts domination comfortably} \item{\code{sCAQ015}}{Skilled in social techniques of imaginative play, pretending, and humor} \item{\code{sCAQ016}}{Introspective and concerned with self as an object} \item{\code{sCAQ017}}{Sympathetic and considerate} \item{\code{sCAQ018}}{Initiates humor} \item{\code{sCAQ019}}{Seeks reassurance from others} \item{\code{sCAQ020}}{Has a rapid personal tempo; behaves and acts quickly} \item{\code{sCAQ021}}{Arouses nurturant feelings in others} \item{\code{sCAQ022}}{Feels a lack of personal meaning in life} \item{\code{sCAQ023}}{Extrapunitive; tends to transfer or project blame} \item{\code{sCAQ024}}{Prides self on being objective,rational} \item{\code{sCAQ025}}{Tends toward over-control of needs and impulses} \item{\code{sCAQ026}}{Productive; gets things done} \item{\code{sCAQ027}}{Shows condescending behavior in relations with others} \item{\code{sCAQ028}}{Tends to arouse liking and acceptance } \item{\code{sCAQ029}}{Turned to for advice and reassurance} \item{\code{sCAQ030}}{Gives up and withdraws where possible in the face of frustration and adversity} \item{\code{sCAQ031}}{Regards self as physically attractive} \item{\code{sCAQ032}}{Aware of the impression made on others} \item{\code{sCAQ033}}{Calm, relaxed in manner} \item{\code{sCAQ034}}{Over-reactive to minor frustrations, irritable} \item{\code{sCAQ035}}{Has warmth; has the capacity for close relationships; compassionate} \item{\code{sCAQ036}}{Subtly negativistic; tends to undermine and obstruct } \item{\code{sCAQ037}}{Guileful and deceitful, manipulative, opportunistic} \item{\code{sCAQ038}}{Has hostility toward others} \item{\code{sCAQ039}}{Thinks and associates ideas in unusual ways; has unconventional thought processes} \item{\code{sCAQ040}}{Vulnerable to real or fancied threat, generally fearful} \item{\code{sCAQ041}}{Moralistic} \item{\code{sCAQ042}}{Reluctant to commit to any definite course of action; tends to delay or avoid action} \item{\code{sCAQ043}}{Facially and/or gesturally expressive} \item{\code{sCAQ044}}{Evaluates the motivation of others in interpreting situations} \item{\code{sCAQ045}}{Has a brittle ego-defense system; does not cope well under stress or strainr} \item{\code{sCAQ046}}{Engages in personal fantasy and daydreams} \item{\code{sCAQ047}}{Has a readiness to feel guilt} \item{\code{sCAQ048}}{Keeps people at a distance; avoids close interpersonal relationships} \item{\code{sCAQ049}}{Basically distrustful of people in general} \item{\code{sCAQ050}}{Unpredictable and changeable in behavior and attitudes} \item{\code{sCAQ051}}{Genuinely values intellectual and cognitive matters} \item{\code{sCAQ052}}{Behaves in an assertive fashion} \item{\code{sCAQ053}}{Unable to delay gratification} \item{\code{sCAQ054}}{Emphasizes being with others; gregarious} \item{\code{sCAQ055}}{Self-defeating} \item{\code{sCAQ056}}{Responds to humor} \item{\code{sCAQ057}}{Interesting, arresting person} \item{\code{sCAQ058}}{Enjoys sensuous experiences (touch, taste, smell, physical contact)} \item{\code{sCAQ059}}{Concerned with own body and adequacy of physiological functioning} \item{\code{sCAQ060}}{Has insight into own motives and behavior} \item{\code{sCAQ061}}{Creates and exploits dependency in people} \item{\code{sCAQ062}}{Tends to be rebellious and non-conforming} \item{\code{sCAQ063}}{Judges self and other in conventional terms} \item{\code{sCAQ064}}{Socially perceptive of a wide range of interpersonal cues} \item{\code{sCAQ065}}{Pushes and tries to stretch limits} \item{\code{sCAQ066}}{Enjoys esthetic impressions; is esthetically reactive} \item{\code{sCAQ067}}{Self-indulgent} \item{\code{sCAQ068}}{Basically anxious} \item{\code{sCAQ069}}{Sensitive to anything that can be construed as a demand} \item{\code{sCAQ070}}{Behaves in an ethically consistent manner} \item{\code{sCAQ071}}{Has high aspiration level for self} \item{\code{sCAQ072}}{Concerned with own adequacy as a person} \item{\code{sCAQ073}}{Tends to perceive many different contexts in sexual terms} \item{\code{sCAQ074}}{Subjectively unaware of self-concern; feels satisfied with self} \item{\code{sCAQ075}}{Has a clear-cut, internally consistent personality} \item{\code{sCAQ076}}{Projects feelings and motivations onto others} \item{\code{sCAQ077}}{Appears straightforward, forthright, candid in dealing with others} \item{\code{sCAQ078}}{Feels cheated and victimized by life; self-pitying} \item{\code{sCAQ079}}{Ruminates and has persistent, preoccupying thoughts} \item{\code{sCAQ080}}{Interested in members of the opposite sex} \item{\code{sCAQ081}}{Physically attractive; good-looking} \item{\code{sCAQ082}}{Has fluctuating moods} \item{\code{sCAQ083}}{Able to see to the heart of important problems} \item{\code{sCAQ084}}{Cheerful} \item{\code{sCAQ085}}{Emphasizes communication through action and non-verbal behavior} \item{\code{sCAQ086}}{Repressive and dissociative tendencies; denies unpleasant thoughts and conflicts} \item{\code{sCAQ087}}{Interprets basically simple and clear-cut situations in complicated and particularizing ways} \item{\code{sCAQ088}}{Personally charming} \item{\code{sCAQ089}}{Compares self to others} \item{\code{sCAQ090}}{Concerned with philosophical problems} \item{\code{sCAQ091}}{Power-oriented; values power in self and others} \item{\code{sCAQ092}}{Has social poise and presence; appears socially at ease} \item{\code{sCAQ093}}{Behaves in gender-appropriate masculine or feminine style and manner} \item{\code{sCAQ094}}{Expresses hostile feelings directly} \item{\code{sCAQ095}}{Tends to offer advice} \item{\code{sCAQ096}}{Values own independence and autonomy} \item{\code{sCAQ097}}{Emotionally bland; has flattened affect} \item{\code{sCAQ098}}{Verbally fluent; can express ideas well} \item{\code{sCAQ099}}{Self-dramatizing; histrionic} \item{\code{sCAQ100}}{Does not vary roles; relates to everyone in the same way} } } \details{ Subjects are listed as Rows (N=205). CAQ items (\code{\link{caq.items}}) (100 items) } \source{ \url{http://psy2.fau.edu/~shermanr/index.html} } \references{ <NAME>., <NAME>., & <NAME>. (2010). Situational similarity and personality predict behavioral consistency. Journal of Personality and Social Psychology, 99(2), 330-343 } \examples{ data(caq) head(caq) data(caq.items)#lets look at the items for the CAQ caq.items } \keyword{datasets} <file_sep>/man/catseye.Rd \name{catseye} \alias{catseye} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Cat's Eye } \description{ A function for plotting summary statistics with error bars and error distributions. } \usage{ catseye(DV, grp = NULL, plotFUN = mean, errFUN = c("ci", "se", "sd"), conf = 0.95, xpoints = NULL, grp.names = NULL, tick = FALSE, ylim = NULL, col = "gray", len = 0, ...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{DV}{ A numeric variable containing raw scores to be summarized in the graph. } \item{grp}{ Either (a) a single variable indicating the grouping factor, (b) a list of variables each indicating a different grouping factors, or (c) NULL (default) in which case only a single bar is graphed.} \item{plotFUN}{ The function used to create the summary statistic. Usually mean is desired. } \item{errFUN}{ A character element indicating the type of error bars to be calculated. There are four possible choices: "ci" (the default) uses a confidence interval for the mean with level indicated by the conf= argument. "se" uses 1 Standard Error from the mean. "sd" uses 1 Standard Deviation from the mean. NULL indicates no error bars/distributions are desired. } \item{conf}{ A numeric between .00 and 1.00, indicating the desired level of confidence if type "ci" is used for the errFUN argument. } \item{xpoints}{ A vector indicating the location on the x-axis for each group. Can be used to create space between certain groups. } \item{grp.names}{ A character vector providing the names for the different groups (conditions). } \item{tick}{ A logical indicating whether tick marks should be drawn on the x-axis for each group. } \item{ylim}{ A numeric vector of length 2 indicating the lower and upper limits of the y-axis. } \item{col}{ A specification of the plotting color for the error distributions. See \code{\link{par}}. } \item{len}{ A numeric indicating the desired length of the error bar "caps" in inches. } \item{\dots}{ Other arguments passed to the plot() function including graphing parameters. } } \details{ This function plots a summary statistic with error bars and distributions using raw data as input. This is different from, and often more convenient and useful, than barplot() which requires the user to compute the values to be plotted and error bars outside of the function. This is a preferred form of presenting group means (rather than bargraphs) because bargraphs tend to suggest more accuracy than in reality (Cumming, 2012, 2013). } \references{ <NAME>. (2012). Understanding the New Statistics: Effect Sizes, Confidence Intervals, and Meta-Analysis. New York: Routledge.\cr <NAME>. (2013). The New Statistics: Why and How. Psychological Science. } \author{ <NAME> } \seealso{ \code{\link{bargraph}} \code{\link{barplot}} \code{\link{egraph}} } \examples{ # A Single Group f <- rnorm(50) catseye(f, conf=.95, xlab="", ylab="DV", las=1) catseye(f, conf=.95, xlab="", ylab="DV", las=1, col="light green", main="Cat's Eye Plot for a Single Group Mean", sub="95 percent CI") # Two Groups f2 <- rnorm(100) g <- rep(1:2, each=50) catseye(f2, grp=g, xlab="Conditions", ylab="DV", grp.names=c("Control", "Experimental"), las=1) catseye(f2, grp=g, conf=.8, xlab="", ylab="DV", grp.names=c("Control", "Experimental"), las=1, col="cyan", main="Two Group Mean Comparison", sub="80 percent CIs") # Three Groups f3 <- c(rnorm(10), rnorm(10, mean=.5), rnorm(10, mean=1, sd=2)) g2 <- rep(1:3, each=10) catseye(f3, grp=g2, conf=.95, xlab="Conditions", ylab="DV", grp.names=c("Group 1", "Group 2", "Group 3"), las=1, col="cyan", main="Three Group Mean Comparison") # A 2 x 2 Design f4 <- rnorm(200) fac1 <- rep(1:2, each=100) fac2 <- rep(3:4, 100) catseye(f4, list(fac1, fac2), xlab="Conditions", ylab="DV", grp.names=c("High/High", "High/Low", "Low/High", "Low/Low"),las=1, col="orange", main="A 2 x 2 Experiment Comparison") # Using the xpoints argument to create visual space catseye(f4, list(fac1, fac2), xlab="Conditions", ylab="DV", grp.names=c("High/High", "High/Low", "Low/High", "Low/Low"),xpoints=c(1,2,4,5), las=1, col="orange", main="A 2 x 2 Experiment Comparison") # A 2 x 3 Design f5 <- rnorm(180) fac1 <- rep(1:2, each=90) fac2 <- rep(3:5, 60) catseye(f5, list(fac1, fac2), xlab="Conditions", ylab="DV", grp.names=c("High/A", "High/B", "High/C", "Low/A", "Low/B","Low/C"), las=1, main="A 2 x 3 Experiment Comparison") # Using the xpoints argument to create visual space catseye(f5, list(fac1, fac2), xlab="Conditions", ylab="DV", grp.names=c("High/A", "High/B", "High/C", "Low/A", "Low/B","Low/C"), xpoints=c(1,2,3,5,6,7), las=1, main="A 2 x 3 Experiment Comparison") } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ graphing } \keyword{ distributions }% __ONLY ONE__ keyword per line <file_sep>/man/e.bars.Rd \name{e.bars} \alias{e.bars} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Error Bars } \description{ A function for plotting error bars onto barplots. } \usage{ e.bars(graph, m, ebl, sides = 2, length = 0) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{graph}{ A vector of x-coordinates at which to plot the error bars. Alternatively, an object resulting from barplot() may be used. } \item{m}{ A vector indicating the centers for each error bar (e.g., group means) } \item{ebl}{ A vector indicating the error bar lengths } \item{sides}{ A numeric indicating whether one-sided or two-sided error bars are desired. } \item{length}{ A numeric indicating the length of the "caps" of the error bars } } \details{ Plots error bars for barplots, but can be used generically for other error bar plotting. } \author{ <NAME> } \seealso{ \code{\link{bargraph}} } \examples{ #making random data y1 <- rnorm(30, mean = 5, sd = 1.5) y2 <- rnorm(30, mean = 8, sd = 1.2) #simple barplot mygraph <- barplot(c(mean(y1),mean(y2)), ylim=c(0,10)) #plotting the error bars library(sciplot) # To get the se() function e.bars(mygraph, c(mean(y1),mean(y2)), ebl=c(se(y1),se(y2)), sides = 2, length = 0.08) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ error bars } \keyword{ plotting }% __ONLY ONE__ keyword per line <file_sep>/man/Profile.r.Rd \name{Profile.r} \alias{Profile.r} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Profile Correlations } \description{ Computes overall and distinctive profile correlations for each observation (row) with item pairs making up the columns in x.set and y.set. } \usage{ Profile.r(x.set, y.set, nomiss = 1, distinct = FALSE, alt = "greater") } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x.set}{ A data.frame or matrix of the first set of variables with columns corresponding to y.set } \item{y.set}{ A data.frame or matrix of the second set of variables with columns corresponding to x.set } \item{nomiss}{ A numeric between .00 and 1.00 specifying the proportion of x-y pairs required to be complete before NA is returned instead of the profile correlation. The default of 1.00 means that if any values are missing an NA will be returned } \item{distinct}{ A logical indicating whether distinctive profile correlations (agreement) between x.set and y.set should be computed. } \item{alt}{ A character string specifying the alternative hypothesis for tests of overall and distinctive agreement against baseline values. Must be one of "greater" (default), "less" or "two-sided". } } \details{ When distinct is set to its default FALSE: For each observational unit a correlation between its x.set and y.set of variables is returned. If the observational unit has less than "nomiss" pairs with missing data the function returns NA as the unit's result When distinct is set to TRUE: The function does the same analysis a when distinct is set to false, but it provides a number of additional results. Following Furr's (2008) discusison of distinctiveness and normativeness, when distinct is set to TRUE the normative (average) Profile of x.set and y.set is computed. These normative Profiles are then used to predict each Profile in their respective set (i.e., the average Profile of x.set is used to predict each Profile (row) in x.set) using linear regression and the residuals for each set are retained. The correlation between the two normative Profiles is computed and returned. Finally, for each observational unit the correlation between the residualized x.set and the residualized y.set are computed and returned. If the unit has less than "nomiss" pairs with missing data the functions returns NA as the unit's result. } \value{ \item{xNorm }{The average (with missing values removed) Profile for x.set.} \item{yNorm }{The average (with missing values removed) Profile for y.set.} \item{Norm.r }{The correlation between the average x.set and average y.set Profiles.} \item{Agreement}{A data.frame containing the overall and distinctive Profile correlations.} \item{Overall}{The column containing the overall Profile agreements. These are the same values as returned by the function when distinct==FALSE.} \item{Distinctive}{The column containing the distinctive Profile agreements.} \item{Test}{A data.frame containing the sample sizes, average Profile agreements, baseline Profile agreements, t-tests against the baseline, and p-values for both Overall and Distinctive Profile correlations.} } \references{ <NAME>. (2008). A framework for Profile similarity: Integrating similarity, normativeness, and distinctiveness. Journal of Personality, 76(5), 1267-1316. } \author{ <NAME> } \note{ Furr's (2008) discussion of distinctiveness uses difference scores rather than the regression approach used by this function, but the conceptual idea surrounding "distinctiveness" is similar. } %% ~Make other sections like Warning with \section{Warning }{....} ~ \seealso{ \code{\link{Profile.reg}} \code{\link{temp.match}} \code{\link{temp.resid}} \code{\link{t.test}} } \examples{ data(acq1) data(caq) #Lets look at Profile correlations between self-report California Adult Q-Sort #ratings of personality and Aquaintance ratings of the same person. head(acq1) head(caq) Profile.r(caq, acq1) # The basic Profile agreements describe.r(Profile.r(caq, acq1)) # Descriptive Statistics for the Agreements # Now let's look at both overall and distinctive agreement myres <- Profile.r(caq, acq1, distinct = TRUE) myres describe.r(myres$Agreement) # The average overall and distinctive agreements } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ accuracy } \keyword{ profile correlations } \keyword{ agreement } \keyword{ distinctiveness } <file_sep>/man/rbqv3.items.Rd \name{rbqv3.items} \alias{rbqv3.items} \docType{data} \title{ RBQ Items } \description{ This is the abreivated content from the Riverside Behavioral Q-Sort version 3 (67 items). } \usage{data(rbqv3.items)} \format{ A data frame with 67 observations on the following variable. \describe{ \item{items}{ {RBQ001 - Interviews others (if present) (e.g., asks a series of questions)} {\cr RBQ002 - Volunteers a large amount of information about self} {\cr RBQ003 - Seems interested in what someone had to say (Disregard whether interest appears "genuine" or "polite")} {\cr RBQ004 - Tries to control the situation (Disregard whether attempts at control succeed or not)} {\cr RBQ005 - Dominates the situation (Disregard intention, e.g., if P dominates the situation "by default" because other(s) present do very little, this item should receive high placement)} {\cr RBQ006 - Appears to be relaxed and comfortable} {\cr RBQ007 - Exhibits social skills (e.g., does things to make other(s) comfortable, keeps conversation moving, entertains or charms other(s))} {\cr RBQ008 - Is reserved and unexpressive (e.g., expresses little affect; acts in a stiff, formal manner)} {\cr RBQ009 - Laughs frequently (Disregard whether laughter appears to be "nervous" or "genuine")} {\cr RBQ010 - Smiles frequently} {\cr RBQ011 - Is physically animated; moves around a great deal} {\cr RBQ012 - Seems to like other(s) present (e.g., would probably like to be friends with them)} {\cr RBQ013 - Exhibits an awkward interpersonal style (e.g., seems to have difficulty knowing what to say, mumbles, fails to respond to other(s)' conversational advances)} {\cr RBQ014 - Compares self to other(s) (whether others are present or not)} {\cr RBQ015 - Shows high enthusiasm and a high energy level} {\cr RBQ016 - Shows a wide range of interests (e.g., talks about many topics)} {\cr RBQ017 - Talks at rather than with other(s) (e.g., conducts a monologue, ignores what others say)} {\cr RBQ018 - Expresses agreement frequently (High placement implies agreement is expressed unusually often, e.g., in response to each and every statement made. Low placement implies unusual lack of expression of agreement.)} {\cr RBQ019 - Expresses criticism (of anybody or anything) (Low placement implies expresses praise)} {\cr RBQ020 - Is talkative (as observed in this situation)} {\cr RBQ021 - Expresses insecurity (e.g., seems touchy or overly sensitive)} {\cr RBQ022 - Shows physical signs of tension or anxiety (e.g., fidgets nervously, voice wavers)(Lack of signs of anxiety = middle placement; low placement = lack of signs under circumstances where you would expect to see them)} {\cr RBQ023 - Exhibits a high degree of intelligence (NB: At issue is what is displayed in the interaction not what may or may not be latent. Thus, give this item high placement only if P actually says or does something of high intelligence. Low placement implies exhibition of low intelligence; medium placement = no information one way or the other)} {\cr RBQ024 - Expresses sympathy (to anyone, i.e., including conversational references)(Low placement implies unusual lack of sympathy)} {\cr RBQ025 - Initiates humor} {\cr RBQ026 - Seeks reassurance (e.g., asks for agreement, fishes for praise)} {\cr RBQ027 - Exhibits condescending behavior (e.g., acts as if self is superior to others [present, or otherwise])(Low placement implies acting inferior)} {\cr RBQ028 - Seems likable (to other(s) present)} {\cr RBQ029 - Seeks advice} {\cr RBQ030 - Appears to regard self as physically attractive} {\cr RBQ031 - Acts irritated} {\cr RBQ032 - Expresses warmth (to anyone, e.g., include any references to "my close friend," etc)} {\cr RBQ033 - Tries to undermine, sabotage or obstruct} {\cr RBQ034 - Expresses hostility (no matter toward whom or what)} {\cr RBQ035 - Is unusual or unconventional in appearance} {\cr RBQ036 - Behaves in a fearful or timid manner} {\cr RBQ037 - Is expressive in face, voice or gestures} {\cr RBQ038 - Expresses interest in fantasy or daydreams (Low placement only if such interest is explicitly disavowed)} {\cr RBQ039 - Expresses guilt (about anything)} {\cr RBQ040 - Keep other(s) at a distance; avoids development of any sort of interpersonal relationship (Low placement implies behavior to get close to other(s))} {\cr RBQ041 - Shows interest in intellectual or cognitive matters (e.g., by discussing an intellectual idea in detail or with enthusiasm)} {\cr RBQ042 - Seems to enjoy the situation} {\cr RBQ043 - Says or does something interesting} {\cr RBQ044 - Says negative things about self (e.g., is self-critical; expresses feelings of inadequacy)} {\cr RBQ045 - Displays ambition (e.g., passionate discussion of career plans, course grades, opportunities to make money)} {\cr RBQ046 - Blames others (for anything)} {\cr RBQ047 - Expresses self-pity or feelings of victimization} {\cr RBQ048 - Expresses sexual interest (e.g., acts attracted to someone present; expresses interest in dating or sexual matters in general)} {\cr RBQ049 - Behaves in a cheerful manner} {\cr RBQ050 - Gives up when faced with obstacles (Low placement implies unusual persistence)} {\cr RBQ051 - Behaves in a stereotypically masculine/feminine style or manner (Apply the usual stereotypes appropriate to the P's sex. Low placement implies behavior stereotypical of the opposite sex)} {\cr RBQ052 - Offers advice} {\cr RBQ053 - Speaks fluently and expresses ideas well} {\cr RBQ054 - Emphasizes accomplishments of self, family or acquaintances (Low placement = emphasizes failures of these individuals)} {\cr RBQ055 - Behaves in a competitive manner (Low placement implies cooperative behavior)} {\cr RBQ056 - Speaks in a loud voice} {\cr RBQ057 - Speaks sarcastically (e.g., says things (s)he does not mean; makes facetious comments that are not necessarily funny)} {\cr RBQ058 - Makes or approaches physical contact with other(s) (Of any sort, including sitting unusually close without touching) (Low placement implies unusual avoidance of physical contact, such as large interpersonal distance)} {\cr RBQ059 - Engages in constant eye contact with someone (Low placement implies unusual lack of eye contact)} {\cr RBQ060 - Seems detached from the situation} {\cr RBQ061 - Speaks quickly (Low placement = speaks slowly)} {\cr RBQ062 - Acts playful} {\cr RBQ063 - Other(s) seek advice from P} {\cr RBQ064 - Concentrates on/works hard at a task (Low placement implies loafing)} {\cr RBQ065 - Engages in physical activity (e.g., works up a sweat)(Low placement = almost completely sedentary)} {\cr RBQ066 - Acts in a self-indulgent manner (e.g., spending, eating, or drinking)(Low placement implies self-denial)} {\cr RBQ067 - Exhibits physical discomfort or pain (High placement = in excess of what seems proportionate; Low placement implies lack of these signs where expected)} } } } \source{ \url{http://psy2.fau.edu/~shermanr/index.html} } \references{ <NAME>., <NAME>., & <NAME>. (2012). Properties of persons and situations related to overall and distinctive personality-behavior congruence. Journal of Research in Personality, 46, 87-101 } \examples{ data(rbqv3.items) rbqv3.items } \keyword{datasets}<file_sep>/man/bfi.set.Rd \name{bfi.set} \alias{bfi.set} \docType{data} \title{ Big Five Invetory Set } \description{ These are Big Five Inventory self ratings of participants from the Riverside Situation Project. } \usage{data(bfi.set)} \format{ A data frame with 205 observations on the following 44 variables. \describe{ \item{\code{sBFI1}}{Is talkative} \item{\code{sBFI2}}{Tends to find fault with others} \item{\code{sBFI3}}{Does a thorough job } \item{\code{sBFI4}}{Is depressed, blue } \item{\code{sBFI5}}{Is original, comes up with new ideas } \item{\code{sBFI6}}{Is reserved } \item{\code{sBFI7}}{Is helpful and unselfish with others } \item{\code{sBFI8}}{Can be somewhat careless } \item{\code{sBFI9}}{Is relaxed, handles stress well } \item{\code{sBFI10}}{Is curious about many different things } \item{\code{sBFI11}}{Is full of energy } \item{\code{sBFI12}}{Starts quarrels with others } \item{\code{sBFI13}}{Is a reliable worker } \item{\code{sBFI14}}{Can be tense } \item{\code{sBFI15}}{Is ingenious, a deep thinker } \item{\code{sBFI16}}{Generates a lot of enthusiasm } \item{\code{sBFI17}}{Has a forgiving nature } \item{\code{sBFI18}}{Tends to be disorganized } \item{\code{sBFI19}}{Worries a lot } \item{\code{sBFI20}}{Has an active imagination } \item{\code{sBFI21}}{Tends to be quiet } \item{\code{sBFI22}}{Is generally trusting } \item{\code{sBFI23}}{Tends to be lazy} \item{\code{sBFI24}}{Is emotionally stable, not easily upset} \item{\code{sBFI25}}{Is inventive} \item{\code{sBFI26}}{Has an assertive personality} \item{\code{sBFI27}}{Can be cold and aloof} \item{\code{sBFI28}}{Perseveres until the task is finished} \item{\code{sBFI29}}{Can be moody} \item{\code{sBFI30}}{Values artistic, aesthetic experiences} \item{\code{sBFI31}}{Is sometimes shy, inhibited} \item{\code{sBFI32}}{Is considerate and kind to almost everyone} \item{\code{sBFI33}}{Does things efficiently} \item{\code{sBFI34}}{Remains calm in tense situations} \item{\code{sBFI35}}{Prefers work that is routine} \item{\code{sBFI36}}{Is outgoing, sociable} \item{\code{sBFI37}}{Is sometimes rude to others} \item{\code{sBFI38}}{Makes plans and follows through with them} \item{\code{sBFI39}}{Gets nervous easily} \item{\code{sBFI40}}{Likes to reflect, play with ideas} \item{\code{sBFI41}}{Has few artistic interests} \item{\code{sBFI42}}{Likes to cooperate with others} \item{\code{sBFI43}}{Is easily distracted} \item{\code{sBFI44}}{Is sophisticated in art, music, or literature} } } \details{ Participants (N=205) are in rows. BFI items (44 items) are in the columns. } \source{ \url{http://psy2.fau.edu/~shermanr/index.html} } \references{ <NAME>., <NAME>., & <NAME>. (2010). Situational similarity and personality predict behavioral consistency. Journal of Personality and Social Psychology, 99(2), 330-343 } \examples{ data(bfi.set) head(bfi.set) } \keyword{datasets} <file_sep>/man/scale2.Rd \name{scale2} \alias{scale2} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Scale } \description{ Returns scores in x after rescaling } \usage{ scale2(x, center = TRUE, scale = TRUE) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ A numeric vector, matrix or data.frame } \item{center}{ A logical indicating whether the scores in the columns in x should have their column means subtracted } \item{scale}{ A logical indicating where the scores in the columns in x should be divided by their column standard deviations } } \details{ The built-in R function scale uses the sample standard deviation when its scale option is set to TRUE. This function uses the population standard deviation instead. } \value{ Returns a variable with dimensions equal to that has been scaled according to the arguments used } \author{ <NAME> } \seealso{ \code{\link{scale}} } \examples{ scale(1:5) scale2(1:5) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ scale } \keyword{ centering }% __ONLY ONE__ keyword per line <file_sep>/man/temp.resid.Rd \name{temp.resid} \alias{temp.resid} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Residuals from Template Prediction } \description{ Returns the residuals for each row of y.set as predicted by the vector of values in template. } \usage{ temp.resid(template, y.set, nomiss = 0.8) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{template}{ A vector of values used to predict the values in the row's of of y.set. The length should be equal to nrow(y.set). } \item{y.set}{ A data.frame or matrix of which the row's are to be predicted by the values in template } \item{nomiss}{ A numeric element between .00 and 1.00 specifying the proportion of x-y pairs required to be complete before NA is returned instead of the regression coefficients. The default of .80 means that if more than 20 percent of the x-y pairs are incomplete an NA will be returned. } } \details{ The vector of scores in template is used to predict each row in y.set and the resulting residuals are returned. } \value{ A data.frame with the same dimensions as y.set is returned containing the residual values after predicting y.set from the template. } \author{ <NAME> } \seealso{ \code{\link{Profile.reg}} \code{\link{Profile.resid}} \code{\link{temp.match}} } \examples{ data(opt.temp) data(caq) # Template Matching # Sometimes we want to know how closely each Profile matches a theoretically # or empirically derived Profile (i.e., a template). # Here is the template for the optimally adjusted person in the CAQ. opt.temp temp.match(opt.temp, caq) # The overall template match scores # Now if we want what is left after removing the template from each profile... caq.opt.resids <- temp.resid(opt.temp, caq) head(caq.opt.resids) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ template matching } \keyword{ residuals }% __ONLY ONE__ keyword per line <file_sep>/man/Profile.reg.Rd \name{Profile.reg} \alias{Profile.reg} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Profile Regression Coefficients } \description{ Returns the regression coefficients for each observation (row) with item pairs making up the columns in x.set and y.set. } \usage{ Profile.reg(x.set, y.set, center = "group", std = FALSE, nomiss = 0.8) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x.set}{ A data.frame or matrix, with the same dimensions as y.set, of which each row is a predictor of the corresponding row in y.set. } \item{y.set}{ A data.frame or matrix, with the same dimensions as x.set, of which each row is to be predicted by the correpsonding row in x.set. } \item{center}{ A character string specifying the type of centering to be done. If "group" (default) is used then each column in x.set is centered on its own column mean. If "grand" is used then each column in x.set is centered on the mean of all data in x.set. If "none" is used then no centering is done. } \item{std}{ A logical vector indicating whether variables should be standardized prior to analysis. The default option (FALSE) does no standardizing. Using TRUE standardizes both the variables in x.set and y.set with centering determined by the center="option". } \item{nomiss}{ A numeric between .00 and 1.00 specifying the proportion of x-y pairs required to be complete before NA is returned instead of the regression coefficients. The default of .80 means that if more than 20 percent of the x-y pairs are incomplete an NA will be returned. } } \details{ For each observational unit, the regression coefficients (slope and intercept) between its variables in x.set and y.set are returned. If fewer than 'nomiss' of the x-y pairs of observations are valid (complete) then NA will be returned for both coefficients. } \value{ Returns a data.frame with 2 columns \item{Intercepts }{Regression Intercepts} \item{Slopes }{Regression Slopes} %% ... } \author{ <NAME> } \seealso{ \code{\link{Profile.r}} \code{\link{temp.match}} \code{\link{lin.coef}} } \examples{ data(acq1) data(caq) #Lets get the regression coeficients for #predicting aquaintance California Adult Q-Set (CAQ) #personality ratings from #self-report CAQ ratings Profile.reg(caq, acq1) # Get descriptives for the results describe(Profile.reg(caq, acq1)) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ regression } \keyword{ profile agreement } <file_sep>/man/reQ.Rd \name{reQ} \alias{reQ} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Forced Q-Sort Distribution } \description{ Replace the values in x with the distribution of values defined by dist. } \usage{ reQ(x, dist, ties = "random") } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ A data.frame, matrix, or numeric vector containing the values to be reQ'd. It is assumed that the rows are to be reQ'd if a matrix or data.frame is given. } \item{dist}{ A numeric vector whose sum must be equal to the length of x. The Q values are assumed to be from 1 to length(dist). The values in dist indicate the number of times each Q value is to be used. } \item{ties}{ A character element passed to the \code{\link{rank}} function indicating how ties should be broken. } } \details{ This function takes a vector of data and "normalizes" it by forcing it to fit a Q-sort distributon (see Block, 1978 for information on the Q-sort method). } \value{ Returns a vector of size x containing data that has been normalized to fit a Q-Sort Distributions } \references{ <NAME>. (1978). The Q-Sort method in personality assessment and psychiatric research. Palo Alto, CA: Consulting Psychologists Press. (Originally published 1961). } \author{ <NAME> } \seealso{ \code{\link{ipsatize}} \code{\link{rank}} } \examples{ data(rate.caq) head(rate.caq) rowMeans(rate.caq) caq.dist = c(5,8,12,16,18,16,12,8,5) caq.reQ = reQ(rate.caq, dist = caq.dist) head(caq.reQ) rowMeans(caq.reQ) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ Q-Sort } \keyword{ Likert-type ratings }% __ONLY ONE__ keyword per line <file_sep>/man/diffPlot.Rd \name{diffPlot} \alias{diffPlot} \alias{diffPlot.default} \alias{diffPlot.formula} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Difference Plot } \description{ A function for creating a Difference Plot between two groups. } \usage{ diffPlot(x, ...) ## Default Method \method{diffPlot}{default}(x, y, plotFUN=mean, errFUN=c("ci", "se", "sd"), conf=.95, grp.names=NULL, var.equal=FALSE, paired=FALSE, ylim=NULL, ...) ## Method for class 'formula' \method{diffPlot}{formula}(formula, data = NULL, plotFUN=mean, errFUN=c("ci", "se", "sd"), conf=.95, grp.names=NULL, var.equal=FALSE, paired=FALSE, ylim=NULL, ...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ A single variable with exactly two levels indicating the grouping factor. If x is a grouping factor, a second argument 'y' must be passed with as numeric vector of data values to be plotted. } \item{y}{ Numeric vector of data values to be plotted } \item{formula}{ A formula of the form lhs ~ rhs where lhs is a numeric vector containing the data values and rhs is a variable with exactly two levels giving the corresponding groups. } \item{data}{ An optional data frame containing the variables in the formula. } \item{plotFUN}{ The function used to create the summary statistic. Usually mean is desired. } \item{errFUN}{ A character element indicating the type of error bars to be calculated. There are four possible choices: "ci" (the default) uses a confidence interval for the mean with level indicated by the conf= argument. "se" uses 1 Standard Error from the mean. "sd" uses 1 Standard Deviation from the mean. NULL indicates no error bars are desired. } \item{conf}{ A numeric indicating the desired level of confidence if type "ci" is used for the errFUN argument. } \item{grp.names}{ A character vector of length 2 providing the names for the two different groups (conditions, time-points). } \item{var.equal}{ A logical indicating whether it should be assumed that the variances of the two groups on the DV are equal. Defaults to FALSE. } \item{paired}{ A logical indicating whether the data are paired. } \item{ylim}{ The limits of the plot on the y-axis. } \item{\dots}{ Other arguments passed to the plot() and axis() functions including graphing parameters (e.g. 'col'). } } \details{ This function creates a difference plot with error bars using raw data as input for either two independent group or dependent measures designs. This is a preferred way of graphical displaying group means that are directly compared (rather than bargraphs) because it provides information about the estimated size of the difference and the accuracy of that estimate (Cumming, 2012). } \references{ <NAME>. (2012). Understanding the New Statistics: Effect Sizes, Confidence Intervals, and Meta-Analysis. New York: Routledge. } \author{ <NAME> } %% ~Make other sections like Warning with \section{Warning }{....} ~ \seealso{ \code{\link{bargraph}} \code{\link{egraph}} } \examples{ # Independent Groups, default method y <- rnorm(100) g <- rep(1:2, each=50) diffPlot(g, y, ylab="DV", xlab="", main="Plot of Means with Floating Axis for Mean Difference", grp.names=c("Control", "Experimental"), sub="Arms Indicate 95 Percent CIs") # Independent Groups, formula method diffPlot(y ~ g, ylab="DV", xlab="", main="Plot of Means with Floating Axis for Mean Difference", grp.names=c("Control", "Experimental"), sub="Arms Indicate 95 Percent CIs") # Dependent Groups library(mvtnorm) myData <- rmvnorm(100, mean=c(0,.4), sigma=matrix(c(1,.8,.8,1), nrow=2, byrow=TRUE)) diffPlot(myData[,1], myData[,2], paired=TRUE, ylab="DV", xlab="", main="Plot of Dependent Means with Floating Axis for Mean Difference", grp.names=c("Time 1", "Time 2"), sub="Arms Indicate 95 Percent CIs") } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ difference plot } \keyword{ bargraph }% __ONLY ONE__ keyword per line <file_sep>/man/vector.splithalf.Rd \name{vector.splithalf} \alias{vector.splithalf} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Split-half Repicability of a Vector (pattern) of Correlations } \description{ Computes the split-half replicability of the vector of linear coefficients (e.g. correlations, covariances) between a single variable (x) and a set of other variables (set). } \usage{ vector.splithalf(x, set, typ = "cor", sims = 100, graph = TRUE, CI = 0.95, minval = -1, seed = 2) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ A numeric vector of the same length as nrow(set). } \item{set}{ A data.frame or matrix of which each column is to be related with x. } \item{typ}{ A character string specifying the type of linear coefficients between x and set to be computed. The default "cor" computes the replicability for the correlations between x and set. The option "XY" computes the replicability for the betas when X predicts Y. The option "YX" computes the replicability for the betas when Y predicts X. The option "betas" computes the replicabilities for both X predicting Y and Y predicting X. Finally, the option "all" computes the replicability for the correlations and the betas. } \item{sims}{ A numeric specifying the number of random splithalves to generate to estimate the true splithalf replicability. } \item{graph}{ A logical indicating whether a graph displaying the the random splithalf values should be printed. } \item{CI}{ A numeric between 0.0 and 1.0 indicating the desired confidence interval for the estimated replicability coefficient. } \item{minval}{ A numeric indicating the minimum replicability value allowed. } \item{seed}{ A numeric specifying the random seed to be used. If set to FALSE, no seed is used. } } \details{ <NAME> (2014) suggest that one way to estimate the replicability of a vector of correlation coefficients between a variable of interest (x) and a set of other variables (set) is to 1) divide one's sample into two equal halves, 2) compute the the correlations between 'x' and 'set' for both samples, 3) compute the correlation between the two resultant vectors of correlations, and 4) adjust the resultant split-sample correlation up using the spearman-brown prophecy formula. This function repeats this procedure "sims" times and returns the average result along with confidence intervals. In addition, this function includes options for getting a replicability coefficient for regression slopes (betas). } \value{ \item{N }{The sample size} \item{Split-half r }{The estimated split-half reliability } \item{SE}{Standard Error of the estimate} \item{Lower Limit }{The Lower Limit of the CI around the split-half reliability} \item{Upper Limit }{The Upper Limit of the CI around the split-half reliability} } \references{ <NAME>. & <NAME>. (2014). Estimating the expected replicability of a pattern of correlations and other measures of association. Multivariate Behavioral Research. 49(1), 17-40. } \author{ <NAME> } \seealso{ \code{\link{vector.alpha}} \code{\link{splithalf.r}} } \examples{ data(RSPdata) data(beh.comp) # Is the pattern of relationships between self reported extraversion and behavior replicable RSPdata$sEXT head(beh.comp) vector.splithalf(RSPdata$sEXT, beh.comp) #split-half reliability = .684 # Might also compare with vector.alpha vector.alpha(RSPdata$sEXT, beh.comp) #alpha = .665 } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ split-half reliability} \keyword{ replicability }% __ONLY ONE__ keyword per line <file_sep>/man/exsitu.Rd \alias{exsitu} \name{exsitu} \docType{data} \title{External Ratings of Situations} \description{ These are ratings of 10 situations (columns) completed by external raters on 8 characteristics (rows). } \usage{data(exsitu)} \format{ A matrix containing ratings of 10 situations (columns) on 8 characteristics (rows). } \details{ Situations are the columns (N=10) and characteristics (N=8) are the rows. } \references{ <NAME>., <NAME>., & <NAME>. (forthcoming). Foundations of situation perception: Towards a psychology of how people form impressions of situations. European Journal of Personality. } \examples{ data(exsitu) exsitu } \keyword{datasets}<file_sep>/man/Profile.norm.Rd \name{Profile.norm} \alias{Profile.norm} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Normativeness } \description{ Computes a number of "normativeness" statistics for a given matrix or data.frame } \usage{ Profile.norm(set, nomiss = 0.8, center = "grand", std = FALSE) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{set}{ A data.frame or matrix. } \item{nomiss}{ A numeric between .00 and 1.00 specifying the proportion of x-y pairs required to be complete before NA is returned instead of the regression coefficients. The default of .80 means that if more than 20 percent of the x-y pairs are incomplete an NA will be returned. } \item{center}{ A character vector specifying the type of centering to be done. If "group" is used then each column in set is centered on its own column mean. If "grand" (default) is used then each column in set is centered on the mean of all data in set. If "none" is used then no centering is done. } \item{std}{ A logical vector indicating whether variables should be standardized prior to analysis. The default option (FALSE) does no standardizing. Using TRUE standardizes the variables set with centering determined by the center="option". } } \details{ This function is largely based on Furr's (2008) discussion of normativeness. For a given data.frame or matrix ("set"), this function computes 1) the mean of all variables (columns) in the set; 2) a jackknifed mean for each row, which is the mean of all variables in the set with its own row's data removed; 3) the correlations with normativeness which are the Profile correlations for the data in the rows of set with the jackknifed mean; 4) the regression coefficients with normativeness which are the jackknifed means predicting their own row; and 5) the residuals for the jackknifed means predicting their own own row. Folliwing Furr (2008) the correlation and regression coefficients can be used as measures of "normativeness" for each row's Profile and the residuals can be used as a measure of "distinctiveness" for each row's Profile. } \value{ \item{Means}{The means of the columns in set after removing missing values.} \item{JackMeans }{A matrix, with the same dimensions as set, of means of set after removing the values in the given row.} \item{Cors }{The correlations between each row in set with it's jackknifed mean.} \item{Regs }{The regression coefficients (intercept and slope) for each row in set as predicted by it's jackknifed mean.} \item{Residuals }{A matrix, with the same dimensions as set, containing the residuals from predicting the rows in set from the jackknifed means.} } \references{ <NAME>. (2008). A framework for Profile similarity: Integrating similarity, normativeness, and distinctiveness. Journal of Personality, 75(5), 1267-1316. } \author{ <NAME> } %% ~Make other sections like Warning with \section{Warning }{....} ~ \seealso{ \code{\link{Profile.r}} \code{\link{Profile.reg}} \code{\link{Profile.resid}} } \examples{ data(caq) caq.norm <- Profile.norm(caq) str(caq.norm) # The Mean CAQ profile caq.norm$Means # The Jackknifed Mean Profiles (the mean profile with its own case removed) head(caq.norm$JackMeans) # The profile correlations between my own CAQ and the Jackknifed Mean profile caq.norm$Cors # The regression coefficients between my own CAQ profile and the Jackknifed Mean profile caq.norm$Regs # The residuals after predicting my own CAQ profile with my Jackknifed Mean profile head(caq.norm$Residuals) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ normativeness } \keyword{ residuals }% __ONLY ONE__ keyword per line <file_sep>/man/item.ICC.Rd \name{item.ICC} \alias{item.ICC} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Item Intra-class Correlations } \description{ Calculates the item (or rater) intra-class correlations for a single item and a composite of the items, following Shrout and Fleiss (1979), for the corresponding columns in each set provided to the function. ICC1: Each target is rated by a different judge and the judges are selected at random. (This is a one-way ANOVA fixed effects model and is found by (MSB- MSW)/(MSB+ (nr-1)*MSW)) ICC2: A random sample of k judges rate each target. The measure is one of absolute agreement in the ratings. Found as (MSB- MSE)/(MSB + (nr-1)*MSE + nr*(MSJ-MSE)/nc) ICC3: A fixed set of k judges rate each target. There is no generalization to a larger population of judges. (MSB - MSE)/(MSB+ (nr-1)*MSE) Then, for each of these cases, is reliability to be estimated for a single rating or for the average of k ratings? (The 1 rating case is equivalent to the average intercorrelation, the k rating case to the Spearman Brown adjusted reliability.) ICC1 is sensitive to differences in means between raters and is a measure of absolute agreement. ICC2 and ICC3 remove mean differences between judges, but are sensitive to interactions of raters by judges. The difference between ICC2 and ICC3 is whether raters are seen as fixed or random effects. ICC1k, ICC2k, ICC3K reflect the means of k raters. } \usage{ item.ICC(set1, set2, ..., omit = TRUE) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{set1}{ \code{A data.frame or matrix with corresponding columns in set2 and any additional sets passed to the function.} } \item{set2}{ \code{A data.frame or matrix with correpsonding columns in set1 and any additional sets passed to the function.} } \item{\dots}{ \code{Additional matrices or data.frames with corresponding columns to set1 and set2 passed to the function.} } \item{omit}{ \code{omit} A logical indicating whether incomplete cases should be omitted from analysis. If set to FALSE and data are missing, warning(s) will result. } } \details{ This function returns the ICCs for the corresponding columns from set1, set2, and each additional set to passed to the function where single item ICCs (ICC[x,1]) composite ICCs (ICC[x,k]) are computed for each group of corresponding columns in the sets. Follow Shrout and Fleiss (1979) for interpretation of the different ICCs. } \value{ A data.frame containing the above described ICCs. } \references{ <NAME>. & <NAME>. (1979). Intraclass correlations: Uses in assessing rater reliability. Psychological Bulletin, 86, 420-428 } \author{ <NAME> } \seealso{ \code{\link{get.ICC}} \code{\link{Profile.ICC}} \code{\link[psych]{ICC}} } \examples{ data(acq1) data(acq2) #lets look at the item ICC between two aquaintance ratings of subjects' personality #on 100 personality traits. Notice the columns of each data.frame are corresponding. names(acq1) names(acq2) item.ICC(acq1, acq2) # We can get the descriptives for these using describe() from the 'psych' package describe(item.ICC(acq1, acq2)) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ Intraclass correlation } \keyword{ Agreement }% __ONLY ONE__ keyword per line <file_sep>/man/decomp.Rd \name{decomp} \alias{decomp} \title{Decomposition of Effects} \description{ A function for decomposing a matrix into its grand mean, row effects, column effects, and unique effects and examining the association of these effects with corresponding effects in another matrix } \usage{ decomp(x, y=NULL, na.rm=TRUE, use="pair") } \arguments{ \item{x}{ A matrix of data to decompose } \item{y}{ An optional criterion matrix of data to examine for componential similarity to x } \item{na.rm}{ A logicial indicating if missing values should be removed } \item{use}{ A character indicating how to handle missing data for correlations } } \details{ Following Cronbach (1955) this function deomposes the data matrices in x and y and returns a number of characerisicts about these matrices including four measures of their similarity. See value section. } \value{ A list containing the following \item{GrandMeanX}{ The grand mean of the x matrix } \item{GrandMeanY}{ The grand mean of the y matrix } \item{RowEffectX}{ The mean of the rows for the x matrix } \item{RowEffectY}{ The mean of the rows for the y matrix } \item{ColEffectX }{ The mean of the columns for the x matrix } \item{ColEffectY}{ The mean of the columns for the y matrix } \item{DecompositionX}{ The unique effects in the X matrix after decomposition } \item{DecompositionY}{ The unique effects in the Y matrix after decomposition } \item{RowUniqueCor}{ A vector containing the correlations between the corresponding rows of the decomposed matrices } \item{ColUniqueCor}{ A vector containing the correaltions between the corresponding columns of the decomposed matrices } \item{VarComp}{ A data.frame containing the variance components for rows, columns, and interactions } \item{Stats}{ A 4 x 1 matrix containing 4 similarity components (only returned if a criterion matrix y is provided)\cr Elevation Accuracy: The grand mean of x minus the grand mean of y \cr Differential Eleveation: The correlation between the row effects \cr Stereotype Accuracy: The correlation between the column effects \cr Differential Accuracy: The correlation between the uniquenesses } } \references{ Cronbach, <NAME>. (1955). Processes affecting scores on "understanding of others" and "assumed similarity." Psychological Bulletin, 52, 177-193. } \examples{ data(exsitu) data(insitu) # Decomposition of the column and row effects of a single data matrix decomp(exsitu) # Decomposition of the column and row effects of two data matrices including # the similarities (correlations) between the row, column, and unqiue effects. decomp(exsitu, insitu) } \keyword{Variance Decomposition} \keyword{Decomposition}<file_sep>/man/q.cor.Rd \name{q.cor} \alias{q.cor} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Q Correlations } \description{ Computes correlations, along with randomization tests (see rand.test), between a variable of interest (x) and a set of other variables (set), and repeats this for each sex. } \usage{ q.cor(x, set, sex, fem = 1, male = 2, tails = 2, sims = 1000, seed = 2) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ A numeric vector of the same length as nrow(set) to be correlated with set. } \item{set}{ A matrix or data.frame with nrow the same as length(x) to be correlated with x. } \item{sex}{ A variable specifying the sex variable in the dataset from which x and set come. } \item{fem}{ An element specifying the code for females in the sex variable. } \item{male}{ An element specifying the code for males in the sex variable. } \item{tails}{ An integer of either 1 or 2 specifying the tails for the p-values for the correlations. } \item{sims}{ The number of randomizations passed to the rand.test() function. } \item{seed}{ The seed passed to the rand.test function. } } \details{ A convenience function for quickly examining the pattern of correlations between a variable of interest "x" and a set of other variables "set". } \value{ A list of class q.cor containing... \item{N}{ The Ns (using complete cases) for the total sample as well as female and male subsamples. } \item{corrs}{ The pattern of correlations between 'x' and 'set' for the combined sample, females, and males ordered by the items in set. } \item{sorted}{ The pattern of correlations between 'x' and 'set' for the combined sample, females, and males ordered by the magnitude of the correlations in the combined sample. } \item{vector.cor}{ The correlation between the female and male patterns of correlations. } } \author{ <NAME> } \note{ Use \code{\link{print}} to quickly summarize the output of a q.cor object. } \seealso{ \code{\link{print.q.cor}} \code{\link{rand.test}} } \examples{ data(RSPdata) data(v2rbq) names(v2rbq) q.obj <- q.cor(RSPdata$sEXT, v2rbq, sex = RSPdata$ssex, fem = 1, male = 2, sims = 1000) q.obj #It is often useful to summarize this object with print. #It might be necessary to adjust size of the width of your console to make this content fit. data(rbqv3.items) rbqv3.items #The item content for the rbq print(q.obj, rbqv3.items, initial = "RBQ", short = TRUE, EXPORT = FALSE) # to export a .csv file change export to a location. } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ q.cor} \keyword{ correlations }% __ONLY ONE__ keyword per line <file_sep>/man/alpha.xci.Rd \name{alpha.xci} \alias{alpha.xci} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Alpha Confidence Interval } \description{ Computes the exact confidence interval for Cronbach's alpha if the item scores have a joint multivariate distribution, following the method outlined by Koning & Franses (2003). } \usage{ alpha.xci(x, k, n, CI = 0.95) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ An alpha coefficient to compute a confidence interval around. } \item{k}{ The number of items on which alpha was computed. } \item{n}{ The number of sampling units (observations) on which alpha was computed. } \item{CI}{ A numeric element between .00 and 1.00 indicating the desired confidence level. } } \details{ Koning & Franses (2003) describe several methods for computing confidence intervals around Cronbach's alpha coefficient. This function returns what Koning and Franses (2003) refer to as the exact confidence interval for alpha if the item scores have a joint multivariate distribution. The confidence interval is asymptomic and not necessarily symmetrical. For more info, see Koning and Franses (2003). } \value{ \item{comp1 }{Lower Limit of confidence interval} \item{comp2 }{Upper Limit of confidence interval} %% ... } \references{ <NAME>. & <NAME>. (2003). Confidence Intervals for Cronbach's Alpha Coefficient values. ERIM Report Series Reference No. ERS-2003-041-MKT. Available at SSRN: http//ssrn.com/abstract=423658 } \author{ <NAME> } %% ~Make other sections like Warning with \section{Warning }{....} ~ \seealso{ \code{\link{alpha.aci}} \code{\link{vector.alpha}} } \examples{ #Compute the asymptotic CI for an observed Cronbach's alpha #of .7 on 200 observaitons for a 10 item scale' alpha.xci(.7,10,200) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ alpha } \keyword{ confidence interval } <file_sep>/man/structSumIPC.Rd \name{structSumIPC} \alias{structSumIPC} \title{ Structural Summary Method for the Interpersonal Circumplex } \description{ Computes scores from the structural summary method (Gurtman, 1992; Gurtman & Pincus, 2003; Wright, Pincus, Conroy, & Hilsenroth, 2009) for the interpresonal circumplex. } \usage{ structSumIPC(x, ord = c("PA", "BC", "DE", "FG", "HI", "JK", "LM", "NO")) } \arguments{ \item{ x }{A matrix or data.frame containing the association values (e.g., correlations) between the variable(s) of interest and the IPC scales. The IPC scales should be the columns and the variable(s) of interest should be the rows. } \item{ord}{A character vector of length eight specifying the order of the IPC scales (columns) in x. By default the function assumes they are in counter-clockwise order starting from the vertical axis at 12:00. } } \details{ This function is used to create a unit-weighted composite of the variables listed in the columns of the matrix or data.frame "set" for each row. The nomiss option lets one specify the proportion of valid cases required for the composite mean to be computed. By default, the mean is computed if at least 80 percent of the data in the the row are valid. } \value{ A data.frame containing the following columns: \item{DOM}{ Item's association with the dominance dimension of the IPC } \item{LOV}{ Item's association with the warmth dimension of the IPC } \item{DEG}{ Item's angle on the IPC grid (from 0 to 360) } \item{AMP}{ Item's discriminant validity; degree to which it corresponds to only a single octant } \item{ELEV}{Item's mean level of assocation across all 8 octants } \item{SStot}{ Item's total sums of squares with the IPC } \item{Rsq}{ Item's goodness-of-fit with the IPC (how well do the summary stats capture the correlations between the item and the octants). } } \references{ <NAME>. (1992). Construct validity of interpersonal personality measures: The Interpresonal Circumplex as a nomological net. Journal of Personality and Social Psychology, 63, 105-118.\cr <NAME>., & <NAME>. (2003). The circumplex model: Methods and research applications. In <NAME> & <NAME> (Eds.), Handbook of psychology: Research methods in psychology (Vol. 2, pp. 407-428). Hoboken, NJ: Wiley.\cr <NAME>., <NAME>., & <NAME>. (2003). Complementarity of interpersonal behavior in dyadic interactions. Personanlity and Social Psychology Bulletin, 29, 1082-1090.\cr <NAME>., <NAME>., <NAME>., & <NAME>. (2009). Integrating methods to optimize circumplex description and comparison of groups. Journal of Personality Assessment, 91, 311-322.\cr } \examples{ # How is the CAQ associated with the IPC? data(caq) # Load the caq data data(beh.comp) #Load Behavioral composite data data(caq.items) #Load CAQ items # Get IPC octant scores from the behavioral composites of the RBQ. PA <- composite(beh.comp[,c(56, 4, 5)]) BC <- composite(beh.comp[,c(17, 27, 54)]) DE <- composite(beh.comp[,c(60, 19, 34)]) FG <- composite(beh.comp[,c(13, 22, 36)]) HI <- composite(beh.comp[,c(50, 21, 26)]) JK <- composite(beh.comp[,c(3, 18, 29)]) LM <- composite(beh.comp[,c(7, 32, 28)]) NO <- composite(beh.comp[,c(15, 20, 62)]) IPC.set <- data.frame(PA,BC,DE,FG,HI,JK,LM,NO) # Put them into one data.frame # Get the correlations between the CAQ and the IPC r <- cor(caq, IPC.set) # Apply the structural summary method to the correlations CAQsum <- structSumIPC(r) CAQsum$items <- caq.items CAQsum # Plot the results (only those with Rsq >= .70) CAQsum.sig <- data.frame(CAQsum[CAQsum$Rsq >= .7,], row.names=1:51) plotDEGcaq <- CAQsum.sig$DEG CAQx <- cos(plotDEGcaq * (pi / 180)) CAQy <- sin(plotDEGcaq * (pi / 180)) plotPOScaq <- ifelse(plotDEGcaq > 90 & plotDEGcaq < 270, 2, 4) plotDEGcaq <- ifelse(plotDEGcaq > 90 & plotDEGcaq < 270, plotDEGcaq + 180, plotDEGcaq) plot(CAQx, CAQy, xlim=c(-2, 2), ylim=c(-2, 2), type="n", xlab="Warmth", ylab="Dominance", font.main=1, main="CAQ and the IPC", xaxt="n", yaxt="n") for(i in 1:51) { text(CAQx[i], CAQy[i], labels=CAQsum.sig$items[i,1], cex=.75, srt=plotDEGcaq[i], pos=plotPOScaq[i]) } # Adding a circle circX <- seq(-1,1, by=.01) circY <- sqrt(1 - circX^2) lines(c(circX,-circX), c(circY,-circY)) lines(c(0,0), c(-1,1)) lines(c(-1,1), c(0,0)) } \keyword{IPC} \keyword{Structural Summary}<file_sep>/man/bargraph.Rd \name{bargraph} \alias{bargraph} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Bar Graph } \description{ A function for plotting bargraphs with error bars. } \usage{ bargraph(DV, grp = NULL, barFUN = mean, errFUN = c("ci", "se", "sd"), sides = 2, conf = 0.95, ...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{DV}{ A numeric variable containing raw scores to be formed into the bars of the bargraph. } \item{grp}{ Either (a) a single variable indicating the grouping factor, (b) a list of variables each indicating a different grouping factor, or (c) NULL (default) in which case only a single bar is graphed. } \item{barFUN}{ The function used to create the bargraph. Usually mean is desired. } \item{errFUN}{ A character element indicating the type of error bars to be calculated.There are four possible choices: "ci" (the default) uses a confidence interval for the mean with level indicated by the conf= argument. "se" uses 1 Standard Error from the mean. "sd" uses 1 Standard Deviation from the mean. NULL indicates no error bars are desired. } \item{sides}{ A numeric indicating whether one-sided or two-sided error bars are desired. } \item{conf}{ A numeric indicating the desired level of confidence if type "ci" is used for the errFUN argument. } \item{\dots}{ Other arguments passed to the barplot() function including graphing parameters (e.g. 'ylim', 'col'). } } \details{ This function plots a bargraph with error bars using raw data as input. This is different from and often more convenient than barplot() which requires the user to compute the values to be plotted and error bars outside of the function. } \author{ <NAME> } \seealso{ \code{\link{barplot}} \code{\link{egraph}} } \examples{ T1=rnorm(100,mean=5,sd=1) times=rep(seq(1,5,1),20) bargraph(DV=T1,grp=times,barFUN=mean,errFUN="ci",conf=.95,ylim=c(0,6)) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ bargraph } \keyword{ error bars }% __ONLY ONE__ keyword per line <file_sep>/man/plotProfile.Rd \name{plotProfile} \alias{plotProfile} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Visualizing Profiles of Scores } \description{ A function for plotting entire profiles of scores for individual observations (e.g., personality profiles) } \usage{ plotProfile(dat, rows = NULL, col = "black", grid = TRUE, grid.col = "lightgray", grid.lty = "dotted", item.names = NULL, ...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{dat}{ A data.frame containing the profiles to be plotted. } \item{rows}{ A numeric vector indicating the desired rows in dat to be plotted. If left NULL, then all rows in dat will be plotted.} \item{col}{ A character vector indicating the colors for the lines. One color for each row should be provided.} \item{grid}{ A logical indicating if a vertical grid on the x-axis tick marks should be drawn.} \item{grid.col}{ A character element indicating the color of grid. } \item{grid.lty}{ A character element indicating the line type of grid. } \item{item.names}{ A character vector indicating the names for the items. If left NULL, the names provided in dat will be used. } \item{\dots}{ Other graphical arguments passed to the plot() function. } } \details{ This function plots the profile of scores across all of the variables (constructs) in dat. This is useful for quickly spotting similarity and differences in profiles for two or more observations.} \author{ <NAME> } \seealso{ \code{\link{scoreTest}} \code{\link{meanif}} \code{\link{scoreItems}} } \examples{ data(bfi) keys.list <- list("agree"=c(-1,2,3,4,5), "conscientious"=c(6,7,8,-9,-10),"extraversion"=c(-11,-12,13,14,15), "neuroticism"=c(16,17,18,19,20),"openness"=c(21,-22,23,24,-25)) out <- scoreTest(bfi, keys.list, nomiss=0, maxScore=6, minScore=1) plotProfile(out, rows=1:3, xlab="", ylab="Score", col=c("red", "blue", "green"), main="Big 5 Profiles for Three Subjects", ylim=c(1,6), item.names=names(out)) legend("bottomleft", legend=rownames(bfi)[1:3], lty=1, col=c("red", "blue", "green"), bty="n") } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ item scoring } \keyword{ composite }% __ONLY ONE__ keyword per line <file_sep>/man/get.ICC.Rd \name{get.ICC} \alias{get.ICC} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Intra-class Correlations } \description{ Calculates the 6 intra-class correlations for the columns in the matrix or data.frame x, where the columns are typically raters or items, following Shrout and Fleiss (1979). } \usage{ get.ICC(x) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ A matrix or data.frame on which to calculate ICCs of the columns. } } \details{ This function is the workhorse function for item.ICC and Profile.ICC. It computes the intra-class correlations for a single item and for the composite of the items in the data.frame or matrix x. Of note, the results should be intepreted with extreme caution if values in x are missing. If possible, the best choice is to remove missing values from x first. } \value{ A matrix containing the values for the six possible intra-class correlations described by Shrout and Fleiss (1979). } \references{ <NAME>. & <NAME>. (1979). Intraclass correlations: Uses in assessing rater reliability. Psychological Bulletin, 86, 420-428 } \author{ <NAME> } \note{ This function is the workhorse function for item.ICC and Profile.ICC. It is rarely used as a stand alone function. } %% ~Make other sections like Warning with \section{Warning }{....} ~ \seealso{ \code{\link{item.ICC}} \code{\link{Profile.ICC}} } \examples{ y <- matrix(rnorm(200), ncol=2) get.ICC(y) } \keyword{ Intraclass correlations } \keyword{ Reliability }% __ONLY ONE__ keyword per line <file_sep>/man/acq.comp.Rd \name{acq.comp} \alias{acq.comp} \docType{data} \title{ Acquaintance CAQ Composite } \description{ This is the composite of two aquaintace CAQ ratings of a participant's personality from the Riverside Situation Project } \usage{data(acq.comp)} \format{ A data frame with 205 observations on the following 100 variables. \describe{ \item{\code{acqCompCAQ001}}{Critical, skeptical, not easily impressed} \item{\code{acqCompCAQ002}}{A genuinely dependable and responsible person} \item{\code{acqCompCAQ003}}{Has a wide range of interests} \item{\code{acqCompCAQ004}}{Talkative} \item{\code{acqCompCAQ005}}{Behaves in a giving way toward others} \item{\code{acqCompCAQ006}}{Fastidious, perfectionistic} \item{\code{acqCompCAQ007}}{Favors conservative values} \item{\code{acqCompCAQ008}}{Appears to have a high degree of intellectual capacity} \item{\code{acqCompCAQ009}}{Uncomfortable with uncertainty and complexity} \item{\code{acqCompCAQ010}}{Anxiety and tension find outlet in bodily symptoms} \item{\code{acqCompCAQ011}}{Protective of those close to him or her} \item{\code{acqCompCAQ012}}{Tends to be self-defensive} \item{\code{acqCompCAQ013}}{Thin-skinned; sensitive to criticism or interpersonal slight} \item{\code{acqCompCAQ014}}{Genuinely submissive; accepts domination comfortably} \item{\code{acqCompCAQ015}}{Skilled in social techniques of imaginative play, pretending, and humor} \item{\code{acqCompCAQ016}}{Introspective and concerned with self as an object} \item{\code{acqCompCAQ017}}{Sympathetic and considerate} \item{\code{acqCompCAQ018}}{Initiates humor} \item{\code{acqCompCAQ019}}{Seeks reassurance from others} \item{\code{acqCompCAQ020}}{Has a rapid personal tempo; behaves and acts quickly} \item{\code{acqCompCAQ021}}{Arouses nurturant feelings in others} \item{\code{acqCompCAQ022}}{Feels a lack of personal meaning in life} \item{\code{acqCompCAQ023}}{Extrapunitive; tends to transfer or project blame} \item{\code{acqCompCAQ024}}{Prides self on being objective,rational} \item{\code{acqCompCAQ025}}{Tends toward over-control of needs and impulses} \item{\code{acqCompCAQ026}}{Productive; gets things done} \item{\code{acqCompCAQ027}}{Shows condescending behavior in relations with others} \item{\code{acqCompCAQ028}}{Tends to arouse liking and acceptance } \item{\code{acqCompCAQ029}}{Turned to for advice and reassurance} \item{\code{acqCompCAQ030}}{Gives up and withdraws where possible in the face of frustration and adversity} \item{\code{acqCompCAQ031}}{Regards self as physically attractive} \item{\code{acqCompCAQ032}}{Aware of the impression made on others} \item{\code{acqCompCAQ033}}{Calm, relaxed in manner} \item{\code{acqCompCAQ034}}{Over-reactive to minor frustrations, irritable} \item{\code{acqCompCAQ035}}{Has warmth; has the capacity for close relationships; compassionate} \item{\code{acqCompCAQ036}}{Subtly negativistic; tends to undermine and obstruct } \item{\code{acqCompCAQ037}}{Guileful and deceitful, manipulative, opportunistic} \item{\code{acqCompCAQ038}}{Has hostility toward others} \item{\code{acqCompCAQ039}}{Thinks and associates ideas in unusual ways; has unconventional thought processes} \item{\code{acqCompCAQ040}}{Vulnerable to real or fancied threat, generally fearful} \item{\code{acqCompCAQ041}}{Moralistic} \item{\code{acqCompCAQ042}}{Reluctant to commit to any definite course of action; tends to delay or avoid action} \item{\code{acqCompCAQ043}}{Facially and/or gesturally expressive} \item{\code{acqCompCAQ044}}{Evaluates the motivation of others in interpreting situations} \item{\code{acqCompCAQ045}}{Has a brittle ego-defense system; does not cope well under stress or strainr} \item{\code{acqCompCAQ046}}{Engages in personal fantasy and daydreams} \item{\code{acqCompCAQ047}}{Has a readiness to feel guilt} \item{\code{acqCompCAQ048}}{Keeps people at a distance; avoids close interpersonal relationships} \item{\code{acqCompCAQ049}}{Basically distrustful of people in general} \item{\code{acqCompCAQ050}}{Unpredictable and changeable in behavior and attitudes} \item{\code{acqCompCAQ051}}{Genuinely values intellectual and cognitive matters} \item{\code{acqCompCAQ052}}{Behaves in an assertive fashion} \item{\code{acqCompCAQ053}}{Unable to delay gratification} \item{\code{acqCompCAQ054}}{Emphasizes being with others; gregarious} \item{\code{acqCompCAQ055}}{Self-defeating} \item{\code{acqCompCAQ056}}{Responds to humor} \item{\code{acqCompCAQ057}}{Interesting, arresting person} \item{\code{acqCompCAQ058}}{Enjoys sensuous experiences (touch, taste, smell, physical contact)} \item{\code{acqCompCAQ059}}{Concerned with own body and adequacy of physiological functioning} \item{\code{acqCompCAQ060}}{Has insight into own motives and behavior} \item{\code{acqCompCAQ061}}{Creates and exploits dependency in people} \item{\code{acqCompCAQ062}}{Tends to be rebellious and non-conforming} \item{\code{acqCompCAQ063}}{Judges self and other in conventional terms} \item{\code{acqCompCAQ064}}{Socially perceptive of a wide range of interpersonal cues} \item{\code{acqCompCAQ065}}{Pushes and tries to stretch limits} \item{\code{acqCompCAQ066}}{Enjoys esthetic impressions; is esthetically reactive} \item{\code{acqCompCAQ067}}{Self-indulgent} \item{\code{acqCompCAQ068}}{Basically anxious} \item{\code{acqCompCAQ069}}{Sensitive to anything that can be construed as a demand} \item{\code{acqCompCAQ070}}{Behaves in an ethically consistent manner} \item{\code{acqCompCAQ071}}{Has high aspiration level for self} \item{\code{acqCompCAQ072}}{Concerned with own adequacy as a person} \item{\code{acqCompCAQ073}}{Tends to perceive many different contexts in sexual terms} \item{\code{acqCompCAQ074}}{Subjectively unaware of self-concern; feels satisfied with self} \item{\code{acqCompCAQ075}}{Has a clear-cut, internally consistent personality} \item{\code{acqCompCAQ076}}{Projects feelings and motivations onto others} \item{\code{acqCompCAQ077}}{Appears straightforward, forthright, candid in dealing with others} \item{\code{acqCompCAQ078}}{Feels cheated and victimized by life; self-pitying} \item{\code{acqCompCAQ079}}{Ruminates and has persistent, preoccupying thoughts} \item{\code{acqCompCAQ080}}{Interested in members of the opposite sex} \item{\code{acqCompCAQ081}}{Physically attractive; good-looking} \item{\code{acqCompCAQ082}}{Has fluctuating moods} \item{\code{acqCompCAQ083}}{Able to see to the heart of important problems} \item{\code{acqCompCAQ084}}{Cheerful} \item{\code{acqCompCAQ085}}{Emphasizes communication through action and non-verbal behavior} \item{\code{acqCompCAQ086}}{Repressive and dissociative tendencies; denies unpleasant thoughts and conflicts} \item{\code{acqCompCAQ087}}{Interprets basically simple and clear-cut situations in complicated and particularizing ways} \item{\code{acqCompCAQ088}}{Personally charming} \item{\code{acqCompCAQ089}}{Compares self to others} \item{\code{acqCompCAQ090}}{Concerned with philosophical problems} \item{\code{acqCompCAQ091}}{Power-oriented; values power in self and others} \item{\code{acqCompCAQ092}}{Has social poise and presence; appears socially at ease} \item{\code{acqCompCAQ093}}{Behaves in gender-appropriate masculine or feminine style and manner} \item{\code{acqCompCAQ094}}{Expresses hostile feelings directly} \item{\code{acqCompCAQ095}}{Tends to offer advice} \item{\code{acqCompCAQ096}}{Values own independence and autonomy} \item{\code{acqCompCAQ097}}{Emotionally bland; has flattened affect} \item{\code{acqCompCAQ098}}{Verbally fluent; can express ideas well} \item{\code{acqCompCAQ099}}{Self-dramatizing; histrionic} \item{\code{acqCompCAQ100}}{Does not vary roles; relates to everyone in the same way} } } \details{ Subjects are listed as Rows (N=205). CAQ items (\code{\link{caq.items}}) (100 items) } \source{ \url{http://psy2.fau.edu/~shermanr/index.html} } \references{ <NAME>., <NAME>., & <NAME>. (2010). Situational similarity and personality predict behavioral consistency. Journal of Personality and Social Psychology, 99(2), 330-343 } \examples{ data(acq.comp) head(acq.comp) #composites of two ratings } \keyword{datasets}
ff25dc05d9be0f35bf3be844116c130197d93ef1
[ "R" ]
69
R
Justin8428/multicon
d01cc51f116e165aabd181ac1df355db35e57b4c
a7389643ea7b3fa36b3d3197c2eb16d34dd2644f
refs/heads/master
<repo_name>eitanzimmerman/crwn-clothing<file_sep>/src/redux/cart/cart.actions.js import {actionTypes} from './cart.types'; export const toggleCartHidden = () =>({ type: actionTypes.TOGGLE_CART_HIDDEN }); export const addItem = (item) => ({ type: actionTypes.ADD_ITEM, payload: item }) export const clearItemFromCart = (item) => ({ type: actionTypes.CLEAR_ITEM_FROM_CART, payload: item }) export const removeItem = item => ({ type: actionTypes.REMOVE_ITEM, payload: item })<file_sep>/src/redux/shop/shop.reducer.js import actionTypes from './shop.types'; const INITIAL_STATE = { collections: null, isFetching: false, errorMessage: '' } const reducer = (state = INITIAL_STATE, action) =>{ switch(action.type) { case actionTypes.FETCH_COLLECTIONS_START: return { ...state, isFetching: true }; case actionTypes.FETCH_COLLECTIONS_SUCCESS: return { ...state, isFetching: false, collections: action.payload }; case actionTypes.FETCH_COLLECTIONS_FAILURE: return { ...state, isFetching: false, errorMessage: action.payload } default: return state } } export default reducer;<file_sep>/src/components/sign-in/signin.component.jsx import React, { useState} from 'react'; import './signin.styles.scss'; import FormInput from '../form-input/form-input.component'; import CostumButton from '../costum-button/costum-button.component'; import {signInWithGoogle, auth} from '../../firebase/firbase.utils'; const SignIn = () => { const [userCredentials, setCredentials] = useState({email: '', password: ''}) const submitFormHandler = async (event) =>{ event.preventDefault(); const {email, password} = userCredentials try { await auth.signInWithEmailAndPassword(email,password) setCredentials({email:'', password:''}) } catch (e) { console.log(e) } } const onChangeHandler = (event) => { const {name, value} = event.target; setCredentials({...userCredentials, [name]:value}) } const { email, password } = userCredentials return( <div className='sign-in'> <h2>I already have an account</h2> <span>Sign in with your email and password</span> <form onSubmit={submitFormHandler}> <FormInput name='email' type='email' label= 'email' value={email} handleChange={onChangeHandler} required/> <FormInput name='password' type='password' label='password' value={password} handleChange={onChangeHandler} required/> <div className='buttons'> <CostumButton type='submit'>Sign In</CostumButton> <CostumButton type='button' isGoogleSignIn onClick={signInWithGoogle}>Sign In with Google</CostumButton> </div> </form> </div> ) } export default SignIn;
a1e19c516e04099be61cb13b8e8bd54fcbf3a26d
[ "JavaScript" ]
3
JavaScript
eitanzimmerman/crwn-clothing
d1cf50e29dc309ca463f0659b803f3f7a94a5852
0e133104b1f33c6896f94eff80ef142266be6715
refs/heads/master
<repo_name>jasonchen77/Data-Structures-and-Algorithms-Projects<file_sep>/assignment4-sorting-jasonchen319/src/FraudDetection.java public class FraudDetection { private final int MIN_SIZE = 5; public int getNumberOfFrauds(int[] dailyExpeditures, int d) { int[] priorDaysExpeditures = new int[d]; int numberOfFrauds = 0; if (d >= dailyExpeditures.length) { throw new IllegalArgumentException(); } for (int i = 0; i < dailyExpeditures.length-d; i++) { int pdeIndex = 0; for (int j = i; j < i + d; j++) { priorDaysExpeditures[pdeIndex] = dailyExpeditures[j]; pdeIndex++; } quickSort(priorDaysExpeditures, 0, priorDaysExpeditures.length-1); double median; int midpoint = d / 2; if (d % 2 == 0) { median = (priorDaysExpeditures[midpoint] + priorDaysExpeditures[midpoint-1])/2.0; } else { median = priorDaysExpeditures[midpoint]; } int dayTriggerAmount = dailyExpeditures[i + d]; if (dayTriggerAmount >= 2*median) { numberOfFrauds++; } } return numberOfFrauds; } public void quickSort(int[] array, int first, int last) { if (last-first+1 < MIN_SIZE) { insertionSort(array); } else { int pivotIndex = partition(array, first, last); quickSort(array, first, pivotIndex-1); quickSort(array, pivotIndex+1, last); } } public int partition(int[] array, int first, int last) { int mid = (first + last)/2; if (Integer.compare(array[first], array[mid])> 0){ swap(array, first, mid); } if (Integer.compare(array[mid], array[last])> 0){ swap(array, mid, last); if (Integer.compare(array[first], array[mid])> 0){ swap(array, first, mid); } } swap(array, mid, last-1); int pivotIndex = last-1; int pivot = array[pivotIndex]; int indexFromLeft = first+1; int indexFromRight = last-2; boolean done = false; while(!done) { while (Integer.compare(array[indexFromLeft], pivot) < 0) { indexFromLeft++; } while (Integer.compare(array[indexFromRight], pivot) > 0) { indexFromRight--; } if (indexFromLeft < indexFromRight) { swap(array, indexFromLeft, indexFromRight); indexFromLeft++; indexFromRight--; } else { done = true; } } swap(array, pivotIndex, indexFromLeft); pivotIndex = indexFromLeft; return pivotIndex; } public static void swap(int[] array, int i, int j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } public static void insertionSort(int[] a) { for(int unsorted = 1; unsorted < a.length; unsorted++) { int firstUnsorted = a[unsorted]; insertInOrder(firstUnsorted, a, 0, unsorted-1); } } public static void insertInOrder(int entryToInsert, int[] a, int begin, int end) { int index = end; while((index >= begin) && (entryToInsert < a[index])){ a[index+1] = a[index]; index--; } a[index+1] = entryToInsert; } } <file_sep>/assignment1-warm-up-java-jasonchen319/Calendar.java public class Calendar { private static final int MAXEVENTS = 4; private Event[] events; private int numEvents; public Calendar() { this.events = new Event[MAXEVENTS]; this.numEvents = 0; } public boolean addEvent(Event e) { if (numEvents < MAXEVENTS) { for(int i = 0; i < MAXEVENTS; i++) { if (events[i] == null) { events[i] = e; numEvents++; break; } } return true; } else { return false; } } public int findEvent(Event e) { for(int i = 0; i < MAXEVENTS-1; i++) { if (events[i] == null) { continue; } else { if (events[i].equals(e)) { return i; } else { continue; } } } if (events[MAXEVENTS-1] != null && events[MAXEVENTS-1].equals(e)) { return MAXEVENTS-1; } else { return -1; } } public boolean removeEvent(Event e) { int eventIndex = this.findEvent(e); if (eventIndex == -1) { return false; } else { events[eventIndex] = null; numEvents--; return true; } } public void dump() { for (int i = 0; i < MAXEVENTS; i++) { if (events[i] != null) { System.out.println(events[i].toString()); } } } } <file_sep>/assignment-10-optional-hands-on-with-graphs-jasonchen319/src/Degree.java /** * The class to store the number of incoming edges (indegree) to a vertex and the number of outgoign edges (outdegree) from a vertex * * * @param <V> */ public class Degree { //Number off incoming edges to a vertex int indegree; //number of outgoing edges from a vertex int outdegree; //Constructor public Degree ( int indegree, int outdegree){ this.indegree= indegree; this.outdegree= outdegree; } //Getter and Setter MNethods public int getIndegree() { return indegree; } public void setIndegree(int indegree) { this.indegree = indegree; } public int getOutdegree() { return outdegree; } public void setOutdegree(int outdegree) { this.outdegree = outdegree; } } <file_sep>/assignment8-hands-on-with-binary-search-tree-jasonchen319/TwoDTree_sol.java import java.util.*; public class TwoDTree_sol { /************* * attributes ************/ TwoDTreeNode root; /*************** * constructor **************/ TwoDTree_sol() { root = null; } /********** * methods *********/ public void add(int x, int y) { root=addNode(x,y,root,0); } public TwoDTreeNode addNode(int x, int y, TwoDTreeNode node, int level) { //Stopping Condition: check to see if the root is null and add the new node to the root if (node == null) { node= new TwoDTreeNode(x,y,null,null); return node; } //IF the node is duplicate then throw an error if (x==node.xCoordinate && y==node.yCoordinate) throw new IllegalArgumentException ("cannot add duplicate item to the tree"); /* * If level is even and x is less than the root's x coordinate or if level is odd and y is less than root's y coordinate * call the add method recursively on the root's left child and increment the level */ if ((level % 2 ==0 && x<=node.xCoordinate)|| (level%2==1 && y<=node.yCoordinate)) node.left = addNode(x,y,node.left,level+1); /* *Else if level is even and x is greater than the root's x coordinate or if level is odd and y is greater than root's y coordinate * call the add method recursively on the root's right child and increment the level */ else if ((level % 2 ==0 && x>node.xCoordinate)|| (level%2==1 && y>node.yCoordinate)) node.right = addNode(x,y,node.right,level+1); return node; } /** * * @param x * @param y * @returns true if a node with the given x and y coordinates exist in the tree. */ public boolean contains(int x, int y) { return findNode(x,y)!=null?true:false; } private TwoDTreeNode findNode(int x, int y) { TwoDTreeNode node=root; int level=0; while(node!=null) { if (node.xCoordinate==x && node.yCoordinate==y ) return node; if((level%2==0 && x<=node.xCoordinate) || (level%2==1 && y<=node.yCoordinate) ) node = node.left; else if((level%2==0 && x>node.xCoordinate) || (level%2==1 && y>node.yCoordinate) ) node = node.right; level++; } return null; } public void levelOrderPrint() { Queue<TwoDTreeNode> queue= new LinkedList<TwoDTreeNode>(); queue.add(root); while (!queue.isEmpty()) { TwoDTreeNode node = queue.poll(); System.out.print("("+node.xCoordinate+ ","+node.yCoordinate+")"); if (node.left !=null) queue.add(node.left); if (node.right!=null) queue.add(node.right); } } private static class TwoDTreeNode { /************* * attributes ************/ int xCoordinate; int yCoordinate; TwoDTreeNode right; TwoDTreeNode left; /*************** * constructors **************/ TwoDTreeNode(int x, int y) { xCoordinate=x; yCoordinate=y; } TwoDTreeNode(int x, int y, TwoDTreeNode leftChild, TwoDTreeNode rightChild) { xCoordinate=x; yCoordinate=y; left = leftChild; right=rightChild; } } public static void main(String[] args){ System.out.println("building a new tree for nodes (30,40)(5,25)(10,12),(70,70),(50,30),(35,40)"); TwoDTree_sol tDTree = new TwoDTree_sol(); tDTree.add(30,40); tDTree.add(30, 50); tDTree.add(5,25); tDTree.add(10,12); tDTree.add(70,70); tDTree.add(50,30); tDTree.add(35,45); System.out.println("level order traversal for this tree is:"); tDTree.levelOrderPrint(); System.out.println("contains(5,25) returned: " + tDTree.contains(5,25) ); System.out.println("contains(10,13) returned: " +tDTree.contains(10,13) ); System.out.println("contains(35,45) returned: " +tDTree.contains(35,45) ); //System.out.println("minx: "+ tDTree.getMinX()); System.out.println("building a new tree for nodes (51,75)(25,40)(10,50),(12,10),(5,90),(70,70)(50,10)(4,1)(60,80)"); tDTree = new TwoDTree_sol(); tDTree.add(51,75); tDTree.add(25,40); tDTree.add(10,50); tDTree.add(12,10); tDTree.add(5,90); tDTree.add(70,70); tDTree.add(50,10); tDTree.add(4,1); tDTree.add(60,80); System.out.println("level order traversal for this tree is:"); tDTree.levelOrderPrint(); // System.out.println("minx: "+ tDTree.getMinX()); System.out.println("contains(51,75) returned: " + tDTree.contains(51,75) ); System.out.println("contains(4,1) returned: " +tDTree.contains(4,1) ); System.out.println("contains(4,90) returned: " +tDTree.contains(4,90) ); System.out.println("Trying to add duplicate item, exception is expected"); tDTree.add(60,80); } }<file_sep>/assignment3-recursive-scheduling-jasonchen319/src/SchedulingDriver.java import java.util.ArrayList; public class SchedulingDriver { public static void main (String[] args) { Activity[] activities = new Activity[4]; activities[0] = new Activity("A", 1, 2); activities[1] = new Activity("B", 2, 5); activities[2] = new Activity("C", 1, 3); activities[3] = new Activity("D", 5, 6); Scheduling s = new Scheduling(); ArrayList<Activity> optimalActivities = s.getOptimalSchedule(1, 7, activities); for (int i = 0; i < optimalActivities.size(); i++) { System.out.println(optimalActivities.get(i).getActivityName()); } } } <file_sep>/assignment1-warm-up-java-jasonchen319/Date.java public class Date implements Comparable<Date> { private int year; private int month; private int day; public Date(int year, int month, int day) throws IllegalArgumentException { if (year < 2014 || year > 2020 || month < 1 || month > 12 || day < 1 || day > 31) { throw new IllegalArgumentException(); } else { this.year = year; this.month = month; this.day = day; } } public int getYear() { return year; } public int getMonth() { return month; } public int getDay() { return day; } public String toString() { return month + "/" + day + "/" + year; } public boolean equals(Object obj) { Date otherDate = (Date)obj; return (this.year == otherDate.year && this.month == otherDate.month && this.day == otherDate.day); } @Override public int compareTo(Date otherDate) { if (this.year - otherDate.year == 0) { if (this.month - otherDate.month == 0) { if (this.day - otherDate.day == 0) { return 0; } else if (this.day - otherDate.day > 0) { return 1; } else { return -1; } } else if (this.month - otherDate.month > 0) { return 1; } else { return -1; } } else if (this.year - otherDate.year > 0) { return 1; } else { return -1; } } } <file_sep>/assignment3-recursive-scheduling-jasonchen319/src/Scheduling.java import java.util.ArrayList; public class Scheduling { int index = 0; int usageIndex = 0; int actualUsage = 0; int maxUsage = 0; ArrayList <Activity> usageActivity = new ArrayList<Activity>(); //Array for keep track of optimal activities public ArrayList<Activity> getOptimalSchedule (int roomStartTime, int roomEndTime, Activity[] activities) { int roomUsage = roomEndTime - roomStartTime; //Base case if (index >= activities.length) { return usageActivity; } // if (index == 0) { // actualUsage = actualUsage + (activities[index].getStopTime() - activities[index].getStartTime()); // } //check if overlap if (activities[index].getStartTime() >= roomStartTime) { actualUsage = actualUsage + (activities[index].getStopTime() - activities[index].getStartTime()); } //Case when the first index is not included if (//maxUsage <= roomUsage && actualUsage <= maxUsage) { index++; getOptimalSchedule(roomStartTime, roomEndTime, activities); //return usageActivity; } //Case when the first index is included if (//maxUsage <= roomUsage && actualUsage > maxUsage) { maxUsage = actualUsage; usageActivity.add(activities[index]); index++; usageIndex++; getOptimalSchedule(activities[index-1].getStopTime(), roomEndTime, activities); //return usageActivity; } return usageActivity; } }
bacb78f4756306e74670cc27822dfdda9c24d623
[ "Java" ]
7
Java
jasonchen77/Data-Structures-and-Algorithms-Projects
abea99ed141e8a76a54f170963838af0cd18eabc
08f688de207dd31d9186fa791693c830b9ea9b65
refs/heads/master
<file_sep>import React from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import { increment, decrement } from '../actions/counter' const Counter = (props) => ( <div> Counter: {props.count} <button onClick={props.increment}>+</button> <button onClick={props.decrement}>-</button> </div> ) Counter.propTypes = { count: PropTypes.number, increment: PropTypes.func.isRequired, decrement: PropTypes.func.isRequired, } /** * mapStateToProps是一个函数。它的作用就是像它的名字那样,建立一个从(外部的)state对象到(UI 组件的)props对象的映射关系。 * 作为函数,mapStateToProps执行后应该返回一个对象,里面的每一个键值对就是一个映射。 * mapStateToProps会订阅 Store,每当state更新的时候,就会自动执行,重新计算 UI 组件的参数,从而触发 UI 组件的重新渲染。 * mapStateToProps的第一个参数总是state对象,还可以使用第二个参数,代表容器组件的props对象。 * 使用ownProps作为参数后,如果容器组件的参数发生变化,也会引发 UI 组件重新渲染。 * connect方法可以省略mapStateToProps参数,那样的话,UI 组件就不会订阅Store,就是说 Store 的更新不会引起 UI 组件的更新。 */ const mapStateToProps = state => ({ count: state.count, }) /** * mapDispatchToProps是connect函数的第二个参数,用来建立 UI 组件的参数到store.dispatch方法的映射。 * 也就是说,它定义了哪些用户的操作应该当作 Action,传给 Store。它可以是一个函数,也可以是一个对象。 * 如果mapDispatchToProps是一个函数,会得到dispatch和ownProps(容器组件的props对象)两个参数。 * 如果mapDispatchToProps是一个对象,它的每个键名也是对应 UI 组件的同名参数,键值应该是一个函数,会被当作 Action creator ,返回的 Action 会由 Redux 自动发出。 */ const mapDispatchToProps = dispatch => ({ increment: () => dispatch(increment()), decrement: () => dispatch(decrement()), }) export default connect(mapStateToProps, mapDispatchToProps)(Counter) <file_sep>import axios from 'axios' import fetchJsonp from 'fetch-jsonp' export default { getAllAddress(){ return fetchJsonp('https://mwpgw.m.jd.com/mwp/mobileDispatch?api=7fresh.address.get&client=m&appName=7fresh').then(function(response){ return response.json() }) }, getDefaultAddress(){ return fetchJsonp('https://mwpgw.m.jd.com/mwp/mobileDispatch?api=7fresh.address.getDefault&client=m&appName=7fresh').then(function(response){ return response.json() }) } }<file_sep>export const ADDRESS_GET_ALL = "ADDRESS_GET_ALL"; export const ADDRESS_GET_ALL_SUCCESSED = 'ADDRESS_GET_ALL_SUCCESSED' export const ADDRESS_GET_ALL_FAILED = 'ADDRESS_GET_ALL_FAILED' export const ADDRESS_GET_DEFAULT = "ADDRESS_GET_DEFAULT"; export const ADDRESS_GET_DEFAULT_SUCCESSED = 'ADDRESS_GET_DEFAULT_SUCCESSED' export const ADDRESS_GET_DEFAULT_FAILED = 'ADDRESS_GET_DEFAULT_FAILED' export function getAll() { return { type: ADDRESS_GET_ALL, } } export function getDefault() { return { type: ADDRESS_GET_DEFAULT, } }<file_sep>import { all, fork, call, put, takeEvery, takeLatest } from 'redux-saga/effects' import services from '../services' export function* fetchData(action) { try { const list = yield call(services.address.getAllAddress); // console.log(list.data.addressInfos); yield put({ type: "ADDRESS_GET_ALL_SUCCESSED", payload: list.data.addressInfos }); } catch (e) { yield put({ type: "ADDRESS_GET_ALL_FAILED", message: e.message }); } } function* rootSaga() { yield takeEvery("ADDRESS_GET_ALL", fetchData); } export default function* root(){ yield all([fork(rootSaga)]) };<file_sep>import React from 'react' import { Link } from 'react-router-dom' const NavBar = () => ( <ul> <li><Link to="/">Home</Link></li> <li><Link to="/hello">Hello</Link></li> <li><Link to="/counter">Counter</Link></li> <li><Link to="/address">Address</Link></li> </ul> ) export default NavBar <file_sep>react react-router redux redux-saga example<file_sep>import React, { Component, PropTypes } from 'react' import {connect} from 'react-redux' // import {Test} from './Test' import {getAll} from '../actions/address' import '../less/address.less' class Address extends Component{ constructor(props) { super(props); // this.state = {isToggleOn: true}; // This binding is necessary to make `this` work in the callback // this.getAddressList = this.getAddressList.bind(this); } render() { return ( <div> <div className="address">address</div> </div> ); } // getAddressList(){ // console.log('getAddressList'); // } } Address.propTypes = { list: PropTypes.array, } const mapStateToProps = state => ({ list: state.address }) // const mapDispatchToProps = dispatch => ({ // getAddressList: () => {dispatch({type: 'ADDRESS_GET_ALL'});} // }) const mapDispatchToProps = { getAll } export default connect(mapStateToProps, mapDispatchToProps)(Address)<file_sep>import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import createSagaMiddleware from 'redux-saga' import { AppContainer } from 'react-hot-loader' import { createHashHistory } from 'history' import { applyMiddleware, compose, createStore } from 'redux' import { connectRouter, routerMiddleware, ConnectedRouter } from 'connected-react-router' // import { routerMiddleware, connectRouter } from 'connected-react-router/immutable' // import Immutable from 'immutable' import saga from './sagas' import App from './App' import rootReducer from './reducers' const history = createHashHistory() const sagaMiddleware = createSagaMiddleware() const initialState = {} // const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose const store = createStore( connectRouter(history)(rootReducer), initialState, compose( applyMiddleware( routerMiddleware(history),sagaMiddleware ), ), ) sagaMiddleware.run(saga) //Provider的唯一功能就是传入store对象 const render = () => { ReactDOM.render( <AppContainer> <Provider store={store}> <ConnectedRouter history={history}> <App history={history} /> </ConnectedRouter> </Provider> </AppContainer>, document.getElementById('react-root') ) } render() // Hot reloading // console.log('test1'); // console.log('hot..............................', module.hot); if (module.hot) { // Reload components module.hot.accept('./App', () => { render() }) // Reload reducers module.hot.accept('./reducers', () => { store.replaceReducer(connectRouter(history)(rootReducer)) }) } <file_sep>import { combineReducers } from 'redux' import counterReducer from './counter' import addressReducer from './address' const rootReducer = combineReducers({ count: counterReducer,//reducer的拆分,可以根据业务将reducer在这里进行拆分 address: addressReducer }) export default rootReducer <file_sep>import address from './address' export default { address: address }<file_sep>import React, { Component, PropTypes } from 'react' import {connect} from 'react-redux' export class Test extends Component{ constructor(props) { super(props); console.log(props); } render() { return ( <div> <div onClick={this.props.onGetAllAddress} >获取地址列表</div> </div> ); } } // const mapStateToProps = state => ({ // list: state.list // }) // const mapDispatchToProps = { // getAddressList: () => {type: 'ADDRESS_GET_ALL'} // } // export default connect(mapStateToProps, mapDispatchToProps)(Test)<file_sep>import React from 'react' import HelloChild from './HelloChild' import {connect} from 'react-redux' const Hello = () => ( <div> <div>Hello</div> <HelloChild /> </div> ) export default connect()(Hello)
c8d2e88245450f92fc13d8c96f46f64a9e8cb677
[ "JavaScript", "Markdown" ]
12
JavaScript
hxmilyy/react
774aeb502e4d502d6b7713338b13c2e5ea69b0f4
dfdf88aeafa4f335719da5efa7c232467007c4ae
refs/heads/master
<repo_name>sophiepoole/bathHacked<file_sep>/main.py #!/usr/bin/env python import os import sqlite3 import math import random from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash # create our little application app = Flask(__name__) app.config.from_object(__name__) DATABASE = os.path.join(app.root_path, 'sqlite_db.db') @app.route('/') def show_landing(): return render_template('home.html') @app.route('/timeline') def show_timeline(): return render_template('timeline.html') # def getMapInfo(name): # # get the existing coordinate system # ds = gdal.Open(name) # old_cs= osr.SpatialReference() # old_cs.ImportFromWkt(ds.GetProjectionRef()) # # create the new coordinate system # wgs84_wkt = """ # GEOGCS["WGS 84", # DATUM["WGS_1984", # SPHEROID["WGS 84",6378137,298.257223563, # AUTHORITY["EPSG","7030"]], # AUTHORITY["EPSG","6326"]], # PRIMEM["Greenwich",0, # AUTHORITY["EPSG","8901"]], # UNIT["degree",0.01745329251994328, # AUTHORITY["EPSG","9122"]], # AUTHORITY["EPSG","4326"]]""" # new_cs = osr.SpatialReference() # new_cs .ImportFromWkt(wgs84_wkt) # # create a transform object to convert between coordinate systems # transform = osr.CoordinateTransformation(old_cs,new_cs) # #get the point to transform, pixel (0,0) in this case # width = ds.RasterXSize # height = ds.RasterYSize # gt = ds.GetGeoTransform() # minx = gt[0] # miny = gt[3] + width*gt[4] + height*gt[5] # maxx = gt[0] + width*gt[1] + height*gt[2] # maxy = gt[3] # #get the coordinates in lat long # sw = transform.TransformPoint(minx,miny) # ne = transform.TransformPoint(maxx, maxy) # sw = (sw[1],sw[0]) # ne = (ne[1], ne[0]) # return (sw,ne) @app.route('/maps') def show_currentMap(): return render_template('mapCurrent.html') @app.route('/maps1572') def show_maps(): url = '../static/1572-jones.jpg' # result = getMapInfo('static/1572-geo.tiff') # print result sw = (51.37664244922259, -2.3664062869774063) ne = (51.3854469338053, -2.3507642429564233) return render_template('maps.html', sw=sw, ne=ne, url=url, year='1572') @app.route('/maps1852') def show_maps2(): url = '../static/bath1852.jpg' # result = getMapInfo('static/1572-geo.tiff') # print result sw = (51.349977143937735, -2.396141436914776) ne = (51.4066626937285, -2.324443744982658) return render_template('maps.html', sw=sw, ne=ne, url=url, year='1852') @app.route('/maps1891') def show_maps1(): url = '../static/bath-1891.jpg' #result = getMapInfo('static/bath-1891-geo.tiff') #print result sw = (51.3707976034083, -2.389822300856615) ne = (51.39919189594104, -2.3322347272066253) return render_template('maps.html', sw=sw, ne=ne, url=url, year='1891') @app.route('/league') def show_league(): temp = query_db("SELECT * FROM score WHERE Postcode IS NOT NULL AND Metric=\"Final\" ORDER BY Score DESC LIMIT 20") count = 1; records =[] for item in temp: recycling = query_db('select score from score where Postcode= \"' + item[1] + '\" and Metric = \"Recycling\"') transport = query_db('select score from score where Ward LIKE \"' + item[2] + '\" and Metric = \"Transport\"') electricity = query_db('select score from score where Ward= \"' + item[2] + '\" and Metric = \"Electricity\" LIMIT 1') gas = query_db('select score from score where Ward= \"' + item[2] + '\" and Metric = \"Gas\"') transport = random.randint(7,9) records.append([count, item[1], item[2], item[4], recycling, transport, electricity, gas]) count = count + 1 return render_template('league.html', records=records) @app.route('/about') def show_about(): return render_template('about.html') @app.teardown_appcontext def close_connection(exception): db = getattr(g, '_database', None) if db is not None: db.close() #Fires up the server if __name__ == '__main__': app.run(debug=True)
97266f5dd03b7801a47af75c10aba40ab6be3ca8
[ "Python" ]
1
Python
sophiepoole/bathHacked
45fdb68ff197edc2e4c83a88202c8f5b774ebdbe
fb6e89e31321a29d89c26cbd379f53c0779ebed7
refs/heads/master
<repo_name>stephencelis/resque_unit<file_sep>/lib/resque_unit/assertions.rb # These are a group of assertions you can use in your unit tests to # verify that your code is using Resque correctly. module ResqueUnit::Assertions # Asserts that +klass+ has been queued into its appropriate queue at # least once. If +args+ is nil, it only asserts that the klass has # been queued. Otherwise, it asserts that the klass has been queued # with the correct arguments. Pass an empty array for +args+ if you # want to assert that klass has been queued without arguments. def assert_queued(klass, args = nil, message = nil) queue = Resque.queue_for(klass) assert_block (message || "#{klass}#{args ? " with #{args.inspect}" : ""} should have been queued in #{queue}: #{Resque.queue(queue).inspect}.") do in_queue?(queue, klass, args) end end # The opposite of +assert_queued+. def assert_not_queued(klass, args = nil, message = nil) queue = Resque.queue_for(klass) assert_block (message || "#{klass}#{args ? " with #{args.inspect}" : ""} should not have been queued in #{queue}.") do !in_queue?(queue, klass, args) end end private def in_queue?(queue, klass, args = nil) !matching_jobs(queue, klass, args).empty? end def matching_jobs(queue, klass, args = nil) if args # retrieve the elements that match klass and args in the queue Resque.queue(queue).select {|e| e[:klass] == klass && e[:args] == args} else # if no args were passed, retrieve all queued jobs that match klass Resque.queue(queue).select {|e| e[:klass] == klass} end end end <file_sep>/test/resque_unit_scheduler_test.rb require 'test_helper' require 'resque_unit_scheduler' class ResqueUnitSchedulerTest < Test::Unit::TestCase def setup Resque.reset! end context "A task that schedules a resque job in 5 minutes" do setup { Resque.enqueue_in(600, MediumPriorityJob) } should "pass the assert_queued(job) assertion" do assert_queued(MediumPriorityJob) end should "pass the assert_queued_in(600, job) assertion" do assert_queued_in(600, MediumPriorityJob) end should "fail the assert_queued_in(300, job) assertion" do assert_raise Test::Unit::AssertionFailedError do assert_queued_in(300, MediumPriorityJob) end end should "pass the assert_not_queued_in(300, job) assertion" do assert_not_queued_in(300, MediumPriorityJob) end end context "A task that schedules a resque job in 5 minutes with arguments" do setup { Resque.enqueue_in(600, JobWithArguments, 1, "test") } should "pass the assert_queued_in(600, JobWithArguments) assertion" do assert_queued_in(600, JobWithArguments) end should "pass the assert_queued_in(600, JobWithArguments, [1, 'test']) assertion" do assert_queued_in(600, JobWithArguments, [1, 'test']) end should "fail the assert_queued_in(600, JobWithArguments, [2, 'test']) assertion" do assert_raise Test::Unit::AssertionFailedError do assert_queued_in(600, JobWithArguments, [2, 'test']) end end end context "A task that schedules a resque job on Sept. 6, 2016 at 6am" do setup do @time = Time.mktime(2016, 9, 6, 6) Resque.enqueue_at(@time, MediumPriorityJob) end should "pass the assert_queued_at(@time, MediumPriorityJob) assertion" do assert_queued_at(@time, MediumPriorityJob) end should "fail the assert_queued_at(@time - 100, MediumPriorityJob) assertion" do assert_raise Test::Unit::AssertionFailedError do assert_queued_at(@time - 100, MediumPriorityJob) end end should "pass the assert_not_queued_at(@time - 100, MediumPriorityJob) assertion" do assert_not_queued_at(@time - 100, MediumPriorityJob) end end end <file_sep>/lib/resque_unit/resque.rb # The fake Resque class. This needs to be loaded after the real Resque # for the assertions in +ResqueUnit::Assertions+ to work. module Resque # Resets all the queues to the empty state. This should be called in # your test's +setup+ method until I can figure out a way for it to # automatically be called. # # If <tt>queue_name</tt> is given, then resets only that queue. def self.reset!(queue_name = nil) if @queue && queue_name @queue[queue_name] = [] else @queue = Hash.new { |h, k| h[k] = [] } end end # Returns an array of all the jobs that have been queued. Each # element is of the form +{:klass => klass, :args => args}+ where # +klass+ is the job's class and +args+ is an array of the arguments # passed to the job. def self.queue(queue_name) self.reset! unless @queue @queue[queue_name] end # Executes all jobs in all queues in an undefined order. def self.run! old_queue = @queue.dup self.reset! old_queue.each do |k, v| while job = v.shift job[:klass].perform(*job[:args]) end end end # Executes all jobs in the given queue in an undefined order. def self.run_for!(queue_name) jobs = self.queue(queue_name) self.reset!(queue_name) while job = jobs.shift job[:klass].perform(*job[:args]) end end # 1. Execute all jobs in all queues in an undefined order, # 2. Check if new jobs were announced, and execute them. # 3. Repeat 3 def self.full_run! until empty_queues? @queue.each do |k, v| while job = v.shift job[:klass].perform(*job[:args]) end end end end # Returns the size of the given queue def self.size(queue_name) self.reset! unless @queue @queue[queue_name].length end # :nodoc: def self.enqueue(klass, *args) queue_name = queue_for(klass) # Behaves like Resque, raise if no queue was specifed raise NoQueueError.new("Jobs must be placed onto a queue.") unless queue_name queue(queue_name) << {:klass => klass, :args => args} end # :nodoc: def self.queue_for(klass) klass.instance_variable_get(:@queue) || (klass.respond_to?(:queue) && klass.queue) end # :nodoc: def self.empty_queues? @queue.all? do |k, v| v.empty? end end end <file_sep>/test/test_helper.rb require 'rubygems' require 'shoulda' require 'resque_unit' require 'sample_jobs' <file_sep>/lib/resque_unit.rb module ResqueUnit end require 'test/unit' require 'resque_unit/resque' require 'resque_unit/errors' require 'resque_unit/assertions' Test::Unit::TestCase.send(:include, ResqueUnit::Assertions) <file_sep>/test/sample_jobs.rb class LowPriorityJob @queue = :low @run = false def self.perform self.run = true end def self.run? @run end def self.run=(value) @run = value end end class MediumPriorityJob def self.queue :medium end end class HighPriorityJob @queue = :high def self.perform end end class JobWithArguments @queue = :medium def self.perform(num, text) end end class JobThatCreatesANewJob @queue = :spawn def self.perform Resque.enqueue(LowPriorityJob) end end class JobThatDoesNotSpecifyAQueue def self.perform end end
fd2fc0af7cc782050ee06dbce9351d405d120925
[ "Ruby" ]
6
Ruby
stephencelis/resque_unit
4dab388a205aaaae22ff215054330905fa9fb6c1
b21b41b3de281b5a84e117d8ad5bf181e8e2b4a2
refs/heads/master
<repo_name>heather999/nersc_dc2_run22_y4_y5<file_sep>/scripts/reorg-y4/remove-unneeded/remove_unneeded_py2.py import os, sys import argparse parser = argparse.ArgumentParser(description='A tutorial of argparse!') parser.add_argument("--indir", required=True, type=str, help="input file") args = parser.parse_args() with open(args.indir) as inputf: dirlist = inputf.readlines() dirlist = [x.strip() for x in dirlist] counter = 0 for x in dirlist : print "cur file " + x retcode = os.popen("unlink %s " % x ).read() <file_sep>/scripts/reorg-y4/move_files.py import os, sys import argparse import glob parser = argparse.ArgumentParser(description='A tutorial of argparse!') parser.add_argument("--indir", required=True, type=str, help="input file") args = parser.parse_args() with open(args.indir) as inputf: dirlist = inputf.readlines() dirlist = [x.strip() for x in dirlist] counter = 0 for x in dirlist : print("cur dir " + x) fileIter = glob.iglob(os.path.join(x,'*/fits/agn_ckpts/*.ckpt')) for f in fileIter : print("file" + f) one, two, three, head, trunc_visit, raft = f.split('-') visit = trunc_visit.zfill(8) print(visit) retcode = os.popen("mkdir -p /global/cfs/cdirs/lsst/production/DC2_ImSim/Run2.2i/sim/extract-y4-y5/%s/agn_ckpts && cp -p %s /global/cfs/cdirs/lsst/production/DC2_ImSim/Run2.2i/sim/extract-y4-y5/%s/agn_ckpts " % (visit,f,visit) ).read() #counter = counter + 1 #if counter % 100 == 0 : # print("At file: " + str(counter)) # <file_sep>/scripts/dups/setup_shifter.sh #!/bin/sh shifter --image=lsstdesc/stack-sims:w_2019_42-sims_w_2019_42-v2 /bin/bash source /opt/software/lsst/stack/loadLSST.bash setup lsst_sims #export STACKCVMFS=/cvmfs/sw.lsst.eu/linux-x86_64 #export LSST_STACK_VERSION=w_2019_42 #module unload python #module swap PrgEnv-intel PrgEnv-gnu #module swap gcc gcc/6.3.0 #module rm craype-network-aries #module rm cray-libsci #module unload craype #export CC=gcc #source $STACKCVMFS/$LSST_STACK_VERSION/loadLSST.bash # Use the /cvmfs distrubtion from IN2P3 #LSST_DISTRIB=$STACKCVMFS/lsst_distrib/$LSST_STACK_VERSION #LSST_SIMS=$STACKCVMFS/lsst_sims/sims_$LSST_STACK_VERSION #EUPS_DIR="${LSST_DISTRIB}/eups/current" #source "${LSST_DISTRIB}/loadLSST.bash" # Tell eups to also use the packages in lsst_sims on top of lsst_distrib #EUPS_PATH=$EUPS_PATH:"${LSST_SIMS}/stack/current" ##setup lsst_distrib #setup -r $LOCALDIR/obs_lsst -j #setup -r $LOCALDIR/pipe_tasks -j echo Now setup any necessary stack packages such as: setup -t w_2019_19 lsst_distrib or setup -t sims_w_2019_19 lsst_sims export OMP_NUM_THREADS=1 <file_sep>/scripts/reorg-y4/link-years/y4-empty-remove.sh #!/bin/bash unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00746674 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00748893 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00751777 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00751855 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00752146 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00752986 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00755164 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00755194 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00769333 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00776402 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00783747 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00788800 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00788808 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00796372 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00797326 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00799059 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00819433 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00880151 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00880163 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00887407 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00896712 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00903673 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00924832 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00924971 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00928517 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00931209 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00932232 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00936406 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00937665 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00938360 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00942484 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00943429 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00943470 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00945642 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00948957 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00948993 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00958714 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00966794 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00966885 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00967513 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00975988 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00976047 <file_sep>/scripts/dups/comparedups-false.py import pickle, itertools import numpy as np import os, sys import argparse def checkpoints_equal(file1, file2): with open(file1, 'rb') as fd: ckpt1 = pickle.load(fd) with open(file2, 'rb') as fd: ckpt2 = pickle.load(fd) num_drawn1 = len(ckpt1['drawn_objects']) num_drawn2 = len(ckpt2['drawn_objects']) if ((ckpt1['drawn_objects'] == ckpt2['drawn_objects']) and all(np.equal(list(ckpt1['images'].values())[0], list(ckpt2['images'].values())[0]).ravel())): return True, file1, 0 elif num_drawn1 >= num_drawn2: return False, file1, num_drawn1 - num_drawn2 return False, file2, num_drawn1 - num_drawn2 parser = argparse.ArgumentParser(description='A tutorial of argparse!') parser.add_argument("--indir", required=True, type=str, help="input file") args = parser.parse_args() with open(args.indir) as inputf: dirlist = inputf.readlines() dirlist = [x.strip() for x in dirlist] good = 0 bad = 0 linecount = 0 first = True for x in dirlist : if first: # print("x: " + x) x1 = x first = False else: x2 = x if len(x2) <= 0: first = True continue if checkpoints_equal(x1, x2): good = good + 1 print(x1 + ' ' + x2 + ' True\n') else: bad = bad + 1 linecount = linecount + 1 if linecount % 10 == 0 : print('pair counter: ' + str(linecount)) print('good: ' + str(good) + ' bad: ' + str(bad)+'\n') <file_sep>/scripts/reorg-y4/link-proja/overlap.sh #!/bin/bash unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R32_S01.ckpt ln -s /global/projecta/projectdirs/lsst/production/DC2_ImSim/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R32_S01.ckpt /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R32_S01.ckpt unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R13_S10.ckpt ln -s /global/projecta/projectdirs/lsst/production/DC2_ImSim/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R13_S10.ckpt /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R13_S10.ckpt unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R11_S12.ckpt ln -s /global/projecta/projectdirs/lsst/production/DC2_ImSim/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R11_S12.ckpt /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R11_S12.ckpt unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R03_S21.ckpt ln -s /global/projecta/projectdirs/lsst/production/DC2_ImSim/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R03_S21.ckpt /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R03_S21.ckpt unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R13_S02.ckpt ln -s /global/projecta/projectdirs/lsst/production/DC2_ImSim/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R13_S02.ckpt /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R13_S02.ckpt unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R02_S00.ckpt ln -s /global/projecta/projectdirs/lsst/production/DC2_ImSim/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R02_S00.ckpt /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R02_S00.ckpt unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R23_S20.ckpt ln -s /global/projecta/projectdirs/lsst/production/DC2_ImSim/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R23_S20.ckpt /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R23_S20.ckpt unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R34_S00.ckpt ln -s /global/projecta/projectdirs/lsst/production/DC2_ImSim/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R34_S00.ckpt /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R34_S00.ckpt unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R03_S20.ckpt ln -s /global/projecta/projectdirs/lsst/production/DC2_ImSim/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R03_S20.ckpt /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R03_S20.ckpt unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R32_S02.ckpt ln -s /global/projecta/projectdirs/lsst/production/DC2_ImSim/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R32_S02.ckpt /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R32_S02.ckpt unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R01_S22.ckpt ln -s /global/projecta/projectdirs/lsst/production/DC2_ImSim/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R01_S22.ckpt /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R01_S22.ckpt unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R23_S12.ckpt ln -s /global/projecta/projectdirs/lsst/production/DC2_ImSim/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R23_S12.ckpt /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y4-wfd/00741720/agn_ckpts/checkpoint-741720-R23_S12.ckpt <file_sep>/scripts/reorg-y4/check_files.py import os, sys import argparse import glob parser = argparse.ArgumentParser(description='A tutorial of argparse!') parser.add_argument("--indir", required=True, type=str, help="input file") args = parser.parse_args() badFiles = open(args.indir+".txt", 'w') with open(args.indir) as inputf: dirlist = inputf.readlines() dirlist = [x.strip() for x in dirlist] counter = 0 for x in dirlist : fileIter = glob.iglob(os.path.join(x,'*.tar')) for f in fileIter : print("cur file " + f) #retcode = os.popen("tar --list -f %s | grep -c 'verification OK'" % f).read() retcode = os.popen("cd %s && tar --list -f %s |& tee $CSCRATCH/dc2-run2.2-y4y5/%d-out " % (x,f,counter) ).read() # if int(retcode) != 1 : # print("Found bad " + f) # badFiles.write(f+"\n") counter = counter + 1 if counter % 100 == 0 : print("At file: " + str(counter)) badFiles.close() <file_sep>/scripts/reorg-y4/link-years/find_empty_py2.py import os, sys import argparse import glob parser = argparse.ArgumentParser(description='A tutorial of argparse!') parser.add_argument("--indir", required=True, type=str, help="input file") args = parser.parse_args() with open(args.indir) as inputf: dirlist = inputf.readlines() dirlist = [x.strip() for x in dirlist] counter = 0 for x in dirlist : #print "cur visit " + x retcode = os.popen("ls /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/%s/agn_ckpts | wc -l" % (x) ).read() #print "retcode: " + retcode if retcode.strip() == '0': print x <file_sep>/scripts/reorg-y4/move_prja_py2.py import os, sys import argparse import glob parser = argparse.ArgumentParser(description='A tutorial of argparse!') parser.add_argument("--indir", required=True, type=str, help="input file") args = parser.parse_args() with open(args.indir) as inputf: dirlist = inputf.readlines() dirlist = [x.strip() for x in dirlist] counter = 0 for x in dirlist : print "cur dir " + x fileIter = glob.iglob(os.path.join(x,'*/agn_ckpts/*.ckpt')) for f in fileIter : print "file: " + f a,b,c,d,e,g,h,i,j,k,visit,m,filename=f.split('/') #print visit #print filename retcode = os.popen("ln -s %s /global/cfs/cdirs/lsst/production/DC2_ImSim/Run2.2i/sim/extract-y4-y5/%s/agn_ckpts/%s " % (f,visit,filename) ).read() <file_sep>/scripts/dups/setup_current_sims.sh #!/bin/sh export STACKCVMFS=/cvmfs/sw.lsst.eu/linux-x86_64 export LSST_STACK_VERSION=w_2019_42 module unload python module swap PrgEnv-intel PrgEnv-gnu module swap gcc gcc/6.3.0 module rm craype-network-aries module rm cray-libsci module unload craype export CC=gcc #source $STACKCVMFS/$LSST_STACK_VERSION/loadLSST.bash # Use the /cvmfs distrubtion from IN2P3 LSST_DISTRIB=$STACKCVMFS/lsst_distrib/$LSST_STACK_VERSION LSST_SIMS=$STACKCVMFS/lsst_sims/sims_$LSST_STACK_VERSION EUPS_DIR="${LSST_DISTRIB}/eups/current" source "${LSST_DISTRIB}/loadLSST.bash" # Tell eups to also use the packages in lsst_sims on top of lsst_distrib EUPS_PATH=$EUPS_PATH:"${LSST_SIMS}/stack/current" #setup lsst_distrib #setup -r $LOCALDIR/obs_lsst -j #setup -r $LOCALDIR/pipe_tasks -j echo Now setup any necessary stack packages such as: setup -t w_2019_19 lsst_distrib or setup -t sims_w_2019_19 lsst_sims export OMP_NUM_THREADS=1 <file_sep>/scripts/dups/finddups.py import os, sys import argparse import glob parser = argparse.ArgumentParser(description='A tutorial of argparse!') parser.add_argument("--indir", required=True, type=str, help="input file") args = parser.parse_args() with open(args.indir) as inputf: dirlist = inputf.readlines() dirlist = [x.strip() for x in dirlist] counter = 0 for x in dirlist : print "cur line " + x one, two = x.split('checkpoint-') print one, two mainname, rest = two.split('.ckpt') print mainname filename = 'checkpoint-' + mainname + '.ckpt' print filename retstr = os.popen("find /global/cfs/cdirs/lsst/production/DC2_ImSim/Run2.2i/sim/grid-y4-y5 -name %s " % filename ).read() print retstr <file_sep>/scripts/reorg-y4/link-years/link_by_year_py2.py import os, sys import argparse import glob parser = argparse.ArgumentParser(description='A tutorial of argparse!') parser.add_argument("--indir", required=True, type=str, help="input file") args = parser.parse_args() with open(args.indir) as inputf: dirlist = inputf.readlines() dirlist = [x.strip() for x in dirlist] counter = 0 for x in dirlist : print "cur visit " + x retcode = os.popen("ln -s /global/cfs/cdirs/lsst/production/DC2_ImSim/Run2.2i/sim/extract-y4-y5/%s /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/%s" % (x, x) ).read() <file_sep>/scripts/reorg-y4/link-years/y5-empty-remove.sh #!/bin/bash unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/00992690 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/00997117 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01000752 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01006106 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01010526 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01011341 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01011347 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01026248 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01036469 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01040759 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01042553 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01046616 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01052937 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01056412 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01139327 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01155650 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01157595 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01165868 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01168344 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01168362 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01170049 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01174470 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01176208 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01177018 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01179130 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01180079 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01182628 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01182666 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01184830 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01187449 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01188343 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01188641 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01189075 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01190778 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01193688 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01193908 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01195286 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01207302 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01207415 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01207514 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01209142 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01209168 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01209610 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01211874 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01213206 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01218330 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01222529 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01227274 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01227907 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01230605 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01231193 unlink /global/cfs/cdirs/lsst/production/DC2_ImSim/temp/Run2.2i/sim/y5-wfd/01231242
cb8dab349ec7173f67e6a4ac6cc5590692842874
[ "Python", "Shell" ]
13
Python
heather999/nersc_dc2_run22_y4_y5
6d099b73dbbe0ad0329d9dd459dd2dfd5f51ca29
3ab8ebb622b74364a21e22b805a78afe57bb9a60
refs/heads/master
<repo_name>sherlaimov/new-crawler<file_sep>/src/config.js import path from 'path'; const publicDir = path.resolve(process.cwd(), 'public'); const viewsDir = path.resolve(publicDir, 'views'); const config = { debug: true, port: 3000, rootDir: __dirname, publicDir: path.resolve(process.cwd(), 'public'), viewsDir: path.resolve(publicDir, 'views'), layoutDir: path.resolve(viewsDir, 'layouts'), secretKey: process.env.SECRET_KEY || 'mybadasskey', db: { dialect: 'mysql', username: 'root', url: process.env.DATABASE_URL || 'mysql://root:@localhost:3306/test', password: '', host: '127.0.0.1', port: 3000, name: 'test', }, }; export default config; <file_sep>/README.md # Web Crawler using NodeJS, Koa and D3 for stats visualization A basic implementation of web crawler with NodeJS. ![N|Solid](https://raw.githubusercontent.com/sherlaimov/new-crawler/master/stats-viz-example.jpg) <file_sep>/src/stats-collector.js import fetch from 'node-fetch'; import PubSub from './emitter'; const output = []; // PubSub.on('data-received', dataHandler); function dataHandler(pagesVisited) { console.log('INSIDE dataHandler'); for (let i = 0; i < 5; i++) { iterate(pagesVisited); console.log(`ITERATION NUMBER ${i}`); } output.length = 0; //Bluebird js? setTimeout(() => { //console.log('************* => OUTPUT <= ****************'); const found = []; const sorted = output .map(function(page, i) { const newObj = {}; newObj.time = []; newObj.size = []; for (let i = 0; i < output.length; i++) { if (page.url === output[i].url) { newObj.url = page.url; newObj.time.push(output[i].time); newObj.size = output[i].size; } } newObj.maxTime = Math.max.apply(Math, newObj.time); newObj.avgTime = Math.round(newObj.time.reduce((a, b) => a + b) / newObj.time.length); newObj.minTime = Math.min.apply(Math, newObj.time); return newObj; }) .filter(function(page, i, arr) { for (let i = 0; i < arr.length; i++) { // if (page.url == arr[i].url && ! found.includes(arr[i].url)) { if (page.url == arr[i].url && found.indexOf(arr[i].url) == -1) { found.push(page.url); return page; } } }); PubSub.emit('data-sorted', sorted); //console.log('************** => SORTED <= *********************'); //console.log(JSON.stringify(sorted, null, 2)); }, 2500); } function iterate(pagesVisited) { pagesVisited.forEach(url => { const infoObj = {}; // console.log(`Collecting stats for page ${page.url}`); // const d = new Date(); const before = new Date().getTime(); return fetch(url) .then(resp => resp.text()) .then(body => { const reqTime = new Date().getTime() - before; infoObj.url = url; infoObj.time = reqTime; infoObj.size = body.length; output.push(infoObj); }) .catch(err => { console.log(err); console.log(`An error has occurred \n code: ${err.code}`); }); }); } <file_sep>/src/main.js import path from 'path'; import Koa from 'koa'; import _ from 'koa-route'; import bodyParser from 'koa-bodyparser'; import morgan from 'koa-morgan'; import serve from 'koa-static'; import IO from 'koa-socket'; import db from './database/loki'; import routes from './routes'; import config from './config'; import dataHandler from './utils/data-handler'; const app = new Koa(); const io = new IO(); app.use(async (ctx, next) => { try { await next(); // next is now a function, await instead of yield } catch (err) { ctx.body = { message: err.message }; ctx.status = err.status || 500; } }); app.context.io = io; app.use(serve(path.join(config.publicDir))); app.use(bodyParser()); app.use(morgan('combined')); app.use(_.get('/', routes.index)); app.use(_.get('/crawl', routes.crawl)); app.use(_.get('/checkData', routes.checkData)); app.use(_.get('/stop', routes.stop)); app.use(_.post('/data', routes.data)); io.attach(app); io.on('join', (ctx, data) => { console.log('join event fired', data); }); app.on('error', err => { console.log('server error', err); }); // process.on('SIGINT', () => { // console.log('\nGracefully shutting down from SIGINT (Ctrl+C)'); // console.log('Disabling Adapter...'); // }); app.listen(3000, () => { // db.loadDatabase({}, err => { // if (err) { // console.log(`Error loading DB : ${err}`); // } else { // console.log('database loaded.'); // const sites = db.getCollection('sites'); // // sites.clear(); // db.saveDatabase(err => { // if (err) console.log(`DB on save attempt error: ${err}`); // console.log('DB removed data only'); // }); // // console.log(sites); // } // }); // sites.chain().remove(); console.log('Listening on port 3000'); }); <file_sep>/src/routes/index.js import { createReadStream } from 'fs'; import PubSub from '../emitter'; import Crawler from '../crawler'; import config from '../config'; import db from '../database/loki'; const crawler = new Crawler(); const routes = {}; routes.index = async (ctx, next) => { const io = ctx.io; const connections = []; io.on('connection', (ctx, data) => { // console.log(socket); const socket = ctx.socket; console.log('io data', data); connections.push(socket); console.log(`Connected: ${connections.length} sockets connected`); crawler.on('live-table', data => { socket.emit('live-table', data); }); socket.on('disconnect', () => { connections.splice(connections.indexOf(socket), 1); console.log(`Disconnected: ${connections.length} sockets connected`); }); }); console.log(JSON.stringify(ctx, null, 2)); ctx.type = 'html'; ctx.body = createReadStream(`${config.rootDir}/../public/views/index.html`); // app.use(serve(path.join(config.rootDir, '/public'))); // await ctx.render('index', { title: 'Basic Crawler Index' }); }; function statsCollector() { const pagesCall = db.collections[0]; const pages = pagesCall.find(); const data = []; const stats = {}; const uniqueURLs = pages.map(page => page.url).filter((url, i, arr) => arr.indexOf(url) === i); uniqueURLs.forEach(url => { const info = {}; const uniqueObj = pagesCall.find({ url }); info.url = url; info.avgTime = Math.round( uniqueObj.map(obj => obj.time).reduce((a, b) => a + b) / uniqueObj.length, ); info.maxTime = Math.max(...uniqueObj.map(obj => obj.time)); info.minTime = Math.min(...uniqueObj.map(obj => obj.time)); info.size = uniqueObj.map(obj => obj.size).pop(); data.push(info); }); stats.avgTime = Math.round(data.map(obj => obj.avgTime).reduce((a, b) => a + b) / data.length); stats.avgMin = Math.min(...data.map(obj => obj.avgTime)); stats.avgMax = Math.max(...data.map(obj => obj.avgTime)); stats.data = data; return stats; } routes.checkData = async ctx => { console.log('checkData'); try { const data = await statsCollector(); ctx.status = 200; ctx.response.set('Content-type', 'application/json'); ctx.body = data; } catch (e) { console.log(e); } }; routes.crawl = async (ctx, next) => { const url = ctx.query.url; if (url) { if (db.getCollection(url) === null) { db.addCollection(url, { // unique: ['id'], // indices: ['id'], // autoupdate: true, }); } else { db.getCollection(url).clear(); } crawler.crawl(ctx.query.url); let resolve; const promise = new Promise((ok, reject) => (resolve = ok)); PubSub.on('data-sorted', data => { console.log(data); resolve(data); PubSub.removeAllListeners('data-sorted'); }); // ctx.response.status = 200; ctx.response.body = await promise; } else { ctx.status = 500; ctx.response.body = { message: `Cannot crawl ${ctx.query.url}, please provide a valid URL` }; } }; routes.stop = async (ctx, next) => { crawler.emit('crawler-stop'); ctx.status = 200; ctx.body = { msg: 'Stop action' }; }; const data = {}; routes.data = async (ctx, next) => { console.log(ctx.body); if (ctx.body.url) { data.data = crawler.crawl(ctx.body.url); ctx.redirect(`${config.url}`); } else { ctx.body = { resp: req.body }; } }; export default routes; <file_sep>/src/database/loki.js import Loki from 'lokijs'; import config from '../config'; const db = new Loki(`${config.rootDir}/database/db.json`, { autosave: true }); db.loadDatabase({}, err => { if (err) { console.log(`Error loading DB : ${err}`); } else { console.log('database loaded.'); // if (db.getCollection('sites') === null) { // db.addCollection('sites', { // unique: ['id'], // // indices: ['id'], // autoupdate: true, // }); // } else { // db.getCollection('sites').clear(); // } // db.saveDatabase(err => { // if (err) { // console.log(`DB on save attempt error: ${err}`); // } // console.log('DB saved from loki.js file'); // }); } }); function lokijsCRUD() { var info; db.loadDatabase({}, function() { //Initial collection info = db.getCollection('info'); if (!info) info = db.addCollection('info'); console.log('Initial info: ', info.data); //Create a user info info.insert({ name: 'phchu', age: 18, }); console.log('Add a user: ', info.data); //Read user's age var user = info.findObject({ name: 'phchu' }); console.log('User ' + user.name + ' is ' + user.age + ' years old.'); //Update user's age user.age = 30; info.update(user); console.log('User ' + user.name + ' is ' + user.age + ' years old.'); //Delete the user info.remove(user); console.log('Collection info: ', info.data); //Save profilesDB.saveDatabase(); }); } export default db; <file_sep>/src/utils/data-handler.js import fetch from 'node-fetch'; import PubSub from '../emitter'; import config from '../config'; import db from '../database/loki'; // db.loadDatabase({}, err => { // if (err) { // console.log(`Error loading DB : ${err}`); // } else { // console.log('database loaded.'); // statsCollector('https://scotch.io/'); // } // }); const ITERATION_TOTAL = 5; // const crawler = new Crawler(); // crawler.on('data-received', dataHandler); PubSub.on('data-received', dataHandler); function visitPage(url) { const start = new Date().getTime(); return fetch(url) .then(resp => resp.text()) .then(body => { const reqTime = new Date().getTime() - start; return { url, time: reqTime, size: body.length, }; }) .catch(err => { console.log(err); console.log('Status code: ' + resp.status); console.log(`An error has occurred \n code: ${error.code}`); }); } function dataHandler(url) { console.log('***=> INSIDE DATAHANDLER <=***'); const pages = db.getCollection(url).find(); const pagesColl = db.getCollection(url); const promises = []; pages.forEach(page => { for (let i = 0; i < ITERATION_TOTAL; i += 1) { promises.push(visitPage(page.url)); } }); Promise.all(promises) .then(results => { console.log('*** Promise.all resolved ****'); pagesColl.insert(results); }) .then(() => { console.log('*** starting statsCollector ****'); return statsCollector(url); }) .then(data => PubSub.emit('data-sorted', data)) .catch(e => console.log(e)); } function statsCollector(url) { const pagesCall = db.getCollection(url); const pages = pagesCall.find(); const data = []; const stats = {}; const uniqueURLs = pages.map(page => page.url).filter((url, i, arr) => arr.indexOf(url) === i); uniqueURLs.forEach(url => { const info = {}; const uniqueObj = pagesCall.find({ url }); info.url = url; info.avgTime = Math.round( uniqueObj.map(obj => obj.time).reduce((a, b) => a + b) / uniqueObj.length, ); info.maxTime = Math.max.apply(Math, uniqueObj.map(obj => obj.time)); info.minTime = Math.min.apply(Math, uniqueObj.map(obj => obj.time)); info.size = uniqueObj.map(obj => obj.size).pop(); data.push(info); }); stats.avgTime = Math.round(data.map(obj => obj.avgTime).reduce((a, b) => a + b) / data.length); stats.avgMin = Math.min.apply(Math, data.map(obj => obj.avgTime)); stats.avgMax = Math.max.apply(Math, data.map(obj => obj.avgTime)); stats.data = data; return stats; } <file_sep>/src/emitter.js import events from 'events'; const emitter = new events.EventEmitter(); let cnt = 0; emitter.on('data-received', e => { cnt++; console.log(`Data-received event triggered ${cnt} times`); }); emitter.on('data-sorted', () => { console.log('*********=> DATA SORTED EVENT <=*********'); }); export default emitter;
a5903f5d04bfd725c4d03afac16459019730078e
[ "JavaScript", "Markdown" ]
8
JavaScript
sherlaimov/new-crawler
05f47ac51890be82254d27fd88e852ab13b6f126
9070124b1d09629c429d5a517a1d0fb3d8a249a9
refs/heads/main
<repo_name>dnsing/XTecTutor<file_sep>/src/app/editarEntrada/editarEntrada.component.ts import { Component, OnInit } from '@angular/core'; import {FormControl, FormGroup, Validators} from "@angular/forms"; import { Router } from '@angular/router'; import { ApiEntradaPropiaService } from '../services/api-entrada-propia.service'; import { ApicomplementosService } from '../services/apicomplementos.service'; import { UserService } from '../Services/login.service'; @Component({ selector: 'app-editarEntrada', templateUrl: './editarEntrada.component.html', styleUrls: ['./editarEntrada.component.scss'] }) export class EditarEntradaComponent implements OnInit { public titulo = '' public abstract = '' public body = '' public carrera = '' public curso = '' public fechaCrear = '' public fechaMod = '' public idEntrada = '' public tema = '' public vistas = 0 public calificacion = '' public visible = '' public listAutores = [] public listComentarios = [] public listCarreras = []; public listCursos = []; public listTemas = []; public user: any[]; public listCarnet = []; carnets: any; constructor( private apiEntradaPropia: ApiEntradaPropiaService, private apicomplementos: ApicomplementosService, private apilogin: UserService, private router: Router ){ this.idEntrada = this.router.getCurrentNavigation().extras.state.example; } validatingForm: FormGroup; ngOnInit() { this.validatingForm = new FormGroup({ loginFormModalEmail: new FormControl('', Validators.email), loginFormModalPassword: new FormControl('', Validators.required), }); this.getEntry(); this.getComplementos(); this.user = this.apilogin.userLogged; } getEntry(){ this.apiEntradaPropia.getEntry(this.idEntrada).subscribe((reply:any) => { console.log(reply); this.titulo = reply.titulo; this.abstract = reply.Abstract; this.body = reply.Body; this.carrera = reply.Carrera; this.curso = reply.Curso; this.fechaCrear = reply.FechaCrear; this.fechaMod = reply.FechaMod; this.idEntrada = reply.IdEntrada; this.tema = reply.Tema; this.vistas = reply.Vistas; this.calificacion = reply.calificacion; this.visible = reply.Visible; this.listAutores = reply.listaAutores; this.listComentarios = reply.listaComentario; }); } editEntry(){ //https://localhost:44395/api/Entrada?IdEntrada=id&titulo=eltitulo&Abstract=cacaca&Body=cacacacaca&autores=carnet1,carnet2&IdCarrera=1&Curso=0&IdTema=0&visible=true this.titulo = (<HTMLInputElement>document.getElementById('titulo')).value; this.abstract = (<HTMLInputElement>document.getElementById('abstract')).value; this.body = (<HTMLInputElement>document.getElementById('body')).value; for(let i in this.listAutores){ this.listCarnet.push(this.listAutores[i].carnet); } for(let i in this.listCarreras){ if (this.carrera == this.listCarreras[i].Nombre){ this.carrera = this.listCarreras[i].IdCarrera; } } for(let i in this.listTemas){ if (this.tema == this.listTemas[i].Nombre){ this.tema = this.listTemas[i].IdTema; } } console.log(this.titulo) console.log(this.abstract) console.log(this.body) console.log(this.listCarnet.join()) console.log(this.carrera) console.log(this.curso) console.log(this.tema) console.log(this.visible.toString()) this.apiEntradaPropia.editEntry(this.idEntrada, this.titulo, this.abstract, this.body, this.listCarnet.join(), this.carrera, this.curso, this.tema, this.visible.toString()).subscribe((reply:any) => { console.log(reply) }); } listcarnet(listcarnet: any) { throw new Error('Method not implemented.'); } getComplementos(){ //Cursos this.apicomplementos.getCursos().subscribe((reply:any) => { console.log(reply); this.listCursos = reply; }); //Carreras this.apicomplementos.getCarreras().subscribe((reply:any) => { this.listCarreras = reply; console.log(this.listCarreras); }); //Temas this.apicomplementos.getTema().subscribe((reply:any) => { console.log(reply); this.listTemas = reply; }); } getCarrera(i){ this.carrera = this.listCarreras[i].IdCarrera; } getCurso(i){ this.curso = this.listCursos[i].Nombre; } getTema(i){ this.tema = this.listTemas[i].IdTema; } deleteAutor(i){ this.titulo = (<HTMLInputElement>document.getElementById('titulo')).value; this.abstract = (<HTMLInputElement>document.getElementById('abstract')).value; this.body = (<HTMLInputElement>document.getElementById('body')).value; const Carnets = []; for(let i in this.listAutores){ Carnets.push(this.listAutores[i].carnet); } for(let i in this.listCarreras){ if (this.carrera == this.listCarreras[i].Nombre){ this.carrera = this.listCarreras[i].IdCarrera; } } for(let i in this.listTemas){ if (this.tema == this.listTemas[i].Nombre){ this.tema = this.listTemas[i].IdTema; } } console.log(Carnets) Carnets.splice(i); console.log(Carnets) this.apiEntradaPropia.editEntry(this.idEntrada, this.titulo, this.abstract, this.body, Carnets[0].toString(), this.carrera, this.curso, this.tema, this.visible.toString()).subscribe((reply:any) => { console.log(reply) }); } get loginFormModalEmail() { return this.validatingForm.get('loginFormModalEmail'); } get loginFormModalPassword() { return this.validatingForm.get('loginFormModalPassword'); } }
8e219a9da2bf5a12f19b3fbb61dd7893481c60c6
[ "TypeScript" ]
1
TypeScript
dnsing/XTecTutor
b599028b097b30b0c6d01c0d21a501b28a1eb3de
d5769a2bc2d2e661db71ed17416948121d33f137
refs/heads/master
<file_sep><?php class Phpfetcher_Manager_Abstract { } ?> <file_sep>Phpfetcher ========== 一个PHP爬虫框架 A PHP web crawler framework 简单的教程请参考:http://blog.reetsee.com/archives/366 A simple guide please refer to:http://blog.reetsee.com/archives/366
db4ff59483a6eaac2f944cc8e28d480fd4296dbb
[ "Markdown", "PHP" ]
2
PHP
ccfeeling/phpfetcher
76055b98590393fb60eced39280b202d052159f9
c51d3a58aeb125df28b7f2263334da63962d667b
refs/heads/master
<file_sep>package Frames; public class MainMenuFrame { } <file_sep>package Frames; import DB.DBUtil; import Tables.MembershipList; import java.awt.*; import java.sql.*; import javax.swing.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class LoginFrame extends JPanel{ private JFrame mainOptionMenu; private JTextField txtUsername; private JPasswordField txtPassword; String username = null; String password = <PASSWORD>; public LoginFrame() { initialize(); } public static void main(String[] args) throws SQLException { LoginFrame.startUpMenu(); } public static void startUpMenu() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { LoginFrame window = new LoginFrame(); window.mainOptionMenu.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } private void initialize() { mainOptionMenu = new JFrame(); mainOptionMenu.setTitle("ScoreKeeper"); mainOptionMenu.setBounds(100, 100, 650, 500); mainOptionMenu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainOptionMenu.getContentPane().setLayout(null); Font typeFont = new Font("SansSerif", Font.BOLD, 20); JLabel label = new JLabel("Login menu:"); label.setFont(new Font("Tahoma", Font.PLAIN, 30)); label.setBounds(15, 16, 415, 33); mainOptionMenu.add(label); //Username label JLabel userLabel = new JLabel("Username:"); userLabel.setFont(new Font("Tahoma", Font.PLAIN, 22)); userLabel.setBounds(50, 66, 415, 33); mainOptionMenu.add(userLabel); //Username text field txtUsername = new JTextField(50); txtUsername.setBounds(50,100,500,35); txtUsername.setFont(typeFont); mainOptionMenu.getContentPane().add(txtUsername); //Password text field JLabel passLabel = new JLabel("Password:"); passLabel.setFont(new Font("Tahoma", Font.PLAIN, 22)); passLabel.setBounds(50, 166, 415, 33); mainOptionMenu.add(passLabel); //Password text field txtPassword = new JPasswordField(50); txtPassword.setBounds(50, 200, 500,35); mainOptionMenu.getContentPane().add(txtPassword); // Login button JButton mainMenuBtn = new JButton("Login"); mainMenuBtn.setFont(new Font("Aria", Font.PLAIN, 24)); mainMenuBtn.setBounds(250, 300, 100, 30); mainMenuBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Set username variables to what's in fields, check DB for matching words getUsername(); getPassword(); // Query DB for matching membership boolean matched = DBUtil.checkCredentials(username, password); // Show message for successful or failed login if (matched) { JOptionPane.showMessageDialog(mainOptionMenu, "Successful Login", "Login", JOptionPane.INFORMATION_MESSAGE); mainOptionMenu.dispose(); } else { JOptionPane.showMessageDialog(mainOptionMenu, "Invalid username or password", "Login", JOptionPane.ERROR_MESSAGE); txtPassword.setText(""); } } }); mainOptionMenu.getContentPane().add(mainMenuBtn); } private void getUsername() { username = txtUsername.getText().trim(); } private void getPassword() { password = new String(txtPassword.getPassword()); } } <file_sep> SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!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 */; /*!40101 SET NAMES utf8 */; -- Database: `scoretracker` USE `scoretracker`; -- Drop tables if they already exist DROP TABLE IF EXISTS `admin`; DROP TABLE IF EXISTS MembershipList; DROP TABLE IF EXISTS ScoreEntry; DROP TABLE IF EXISTS TournamentList; CREATE TABLE IF NOT EXISTS `admin` ( `Admin_ID` int(11) NOT NULL AUTO_INCREMENT, `User_Name` varchar(50) NOT NULL, `Password` varchar(50) NOT NULL, PRIMARY KEY (`Admin_ID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; CREATE TABLE IF NOT EXISTS MembershipList ( User_ID int (11) NOT NULL AUTO_INCREMENT, User_Name varchar(50) NOT NULL, Password varchar(50) NOT NULL, PRIMARY KEY (User_Id) ); CREATE TABLE IF NOT EXISTS ScoreEntry( Score_ID int (11) NOT NULL AUTO_INCREMENT PRIMARY KEY, Tourney_ID int (11), Player_ID int (11), Score_Number int (11) NOT NULL, CONSTRAINT fkTourneyId FOREIGN KEY (Tourney_ID) REFERENCES TournamentList (Tourney_ID), CONSTRAINT fkPlayerId FOREIGN KEY (Player_ID) REFERENCES MembershipList (User_ID) ); CREATE TABLE IF NOT EXISTS TournamentList( Tourney_ID int (11) NOT NULL AUTO_INCREMENT PRIMARY KEY, Tourney_Name varchar(50), Score_ID int (11), Num_Players int (11) NOT NULL, CONSTRAINT fkScoreId FOREIGN KEY (Score_ID) REFERENCES ScoreEntry (Score_ID) ); -- -- Dumping data for table `admin` -- INSERT INTO `admin` (`Admin_ID`, `User_Name`, `Password`) VALUES (1, 'explorerone', '<PASSWORD>'); INSERT INTO `MembershipList` (User_ID, User_Name, Password) VALUES (1, "henry", "<PASSWORD>"); INSERT INTO `MembershipList` (User_ID, User_Name, Password) VALUES (2, "dio", "<PASSWORD>"); <file_sep>package Tables; import java.sql.ResultSet; import java.sql.SQLException; public class MembershipList { public static void displayData(ResultSet rs) throws SQLException { while (rs.next()) { StringBuffer buffer = new StringBuffer(); buffer.append("Member " + rs.getInt("User_ID") + ": "); buffer.append(rs.getString("User_Name")); System.out.println(buffer.toString()); System.out.println("Hello"); } } public static void getUsers() { } }
757df9f652b76afe7a6d0f7afc6bd08d0ddd1240
[ "Java", "SQL" ]
4
Java
Tusk98/ScoreTrackerApp
e52e245b6dd1ea341d5d06c9537ff28d8e67218e
24edf246a8d1ef19c0fca5eb2a9f24703f9dc188
refs/heads/master
<repo_name>rensa/ggclump<file_sep>/R/hello.R # Hello, world! # # This is an example function named 'hello' # which prints 'Hello, world!'. # # You can learn more about package authoring with RStudio at: # # http://r-pkgs.had.co.nz/ # # Some useful keyboard shortcuts for package authoring: # # Build and Reload Package: 'Cmd + Shift + B' # Check Package: 'Cmd + Shift + E' # Test Package: 'Cmd + Shift + T' # for now this is basically just position_dodge.r; once i figure out how it # works i can start modifying. # because the forces in d3 are iterative (ie. they continually advance one # step at a time, since they're used in interactive contexts), my solution will # have to decide when the positions have converged. that could be interesting. hello <- function() { print("Hello, world!") } position_clump <- function(seed = NA) { # assign a random seed if one isn't given if (!is.null(seed) && is.na(seed)) { seed <- sample.int(.Machine$integer.max, 1L) } ggproto(NULL, PositionClump, # width = width, # height = height, seed = seed ) } # size oughtn't be a required aesthetic here, but it sure would be useful. # how can i get access to it if it isn't required? maybe inside data? i # need to set up somebreakpoints, i think # also need to know the geom... this could get super weird for things that # aren't points. #' @rdname ggplot2-ggproto #' @format NULL #' @usage NULL #' @export PositionClump <- ggproto( "PositionClump", Position, required_aes = c("x", "y"), setup_params = function(self, data) { list( width = self$width %||% (resolution(data$x, zero = FALSE) * 0.4), height = self$height %||% (resolution(data$y, zero = FALSE) * 0.4), seed = self$seed ) }, compute_layer = function(data, params, panel) { trans_x <- if (params$width > 0) function(x) jitter(x, amount = params$width) trans_y <- if (params$height > 0) function(x) jitter(x, amount = params$height) with_seed_null(params$seed, transform_position(data, trans_x, trans_y)) } )
55987f74ca27ce9b370229b218dbb9a9a4c8e77f
[ "R" ]
1
R
rensa/ggclump
8c499672fb90354f39409883b4aa3dc23a84dbe9
c57b022ece9be086e0a463bbb3ea15e5af2cc79f
refs/heads/master
<repo_name>lennonchoong/Pathfinder-Algorithm-Visualizer<file_sep>/algorithms/dijkstras.js import {create2DArr} from '../mazegenerator.js' import {locateStartNode, locateEndNode} from './algorithmhelper.js' export {dijkstras} function dijkstras(speed) { let arr = create2DArr(); let result = dijkstrasUtil(speed); let path = result[0]; let speedTotal = result[1]; if (path) { for (let i = 2; i < path.length - 1; i ++) { setTimeout(() => { arr[path[i][0]][path[i][1]].classList.add('shortestPathNode'); arr[path[i][0]][path[i][1]].classList.remove('weightedCell'); }, speedTotal); speedTotal += (+speed + 3); } } return speedTotal } function dijkstrasUtil(speed) { let queue = []; let matrix = create2DArr(); let start = locateStartNode(matrix); let end = locateEndNode(matrix); let speedTotal = 0; queue.push([0, [null, start]]); while (queue.length > 0) { queue.sort((a, b) => a[0] - b[0]); let path = queue.shift()[1]; let pos = path[path.length-1]; // ... and then the last position from it let direction = [ [pos[0] + 1, pos[1]], [pos[0], pos[1] + 1], [pos[0] - 1, pos[1]], [pos[0], pos[1] - 1], ]; for (let i = 0; i < direction.length; i++) { let weight = manhattanDist(start, direction[i]); // Perform this check first: if (direction[i][0] == end[0] && direction[i][1] == end[1]) { // return the path that led to the find highlightCurNode(matrix[pos[0]][pos[1]], speedTotal); speedTotal += +speed; highlightSearching(matrix[pos[0]][pos[1]], speedTotal); speedTotal += +speed; return [path.concat([end]), speedTotal] } if (direction[i][0] < 0 || direction[i][0] >= matrix.length || direction[i][1] < 0 || direction[i][1] >= matrix[0].length || matrix[direction[i][0]][direction[i][1]].classList.contains('visitedCell') || matrix[direction[i][0]][direction[i][1]].classList.contains('startNode') || matrix[direction[i][0]][direction[i][1]].classList.contains('selectedCell')) { continue; } if (matrix[direction[i][0]][direction[i][1]].classList.contains('weightedCell')) { weight = 1; } matrix[direction[i][0]][direction[i][1]].classList.add('visitedCell'); queue.push([weight, path.concat([direction[i]])]); } if (matrix[pos[0]][pos[1]].classList.contains('startNode')) continue; highlightCurNode(matrix[pos[0]][pos[1]], speedTotal); speedTotal += +speed; highlightSearching(matrix[pos[0]][pos[1]], speedTotal); speedTotal += +speed; } return [null, speedTotal] } function manhattanDist(nodeA, nodeB) { return Math.abs(nodeA[0] - nodeB[0]) + Math.abs(nodeA[1] - nodeB[1]) } function highlightSearching(cell, speed) { setTimeout(() => { cell.classList.add('highlightSearching'); cell.classList.remove('curNode'); }, speed); } function highlightCurNode(cell, speed) { setTimeout(() => cell.classList.add('curNode') , speed); }<file_sep>/README.md # Pathfinder-Algorithm-Visualizer Check the project out [**here**](https://lennonchoong.github.io/Pathfinder-Algorithm-Visualizer/)! # About This Project This project visualizes the various pathfinding algorithms in traversing a grid with obstacles \& mazes. I built this project out of curiosity on pathfinding algorithms \& to showcase my skills in web development with JavaScript. <file_sep>/algorithms/depthFirstSearch.js import {create2DArr} from '../mazegenerator.js' import {locateStartNode, locateEndNode} from './algorithmhelper.js' export {depthFirstSearch} function depthFirstSearch(speed) { let arr = create2DArr(); let result = depthFirstSearchUtil(speed); let path = result[0]; let speedTotal = result[1]; if (path) { for (let i = 1; i < path.length - 2; i ++) { setTimeout(() => arr[path[i][0]][path[i][1]].classList.add('shortestPathNode'), speedTotal); speedTotal += (+speed + 3); } } return speedTotal } function depthFirstSearchUtil(speed) { let stack = []; let matrix = create2DArr(); let start = locateStartNode(matrix); let end = locateEndNode(matrix); let speedTotal = 0; stack.push([start]); // store a path, not just a position while (stack.length > 0) { let path = stack.pop(); // get the path out of the stack let pos = path[path.length-1]; // ... and then the last position from it let direction = [ [pos[0], pos[1] - 1], [pos[0], pos[1] + 1], [pos[0] + 1, pos[1]], [pos[0] - 1, pos[1]], ]; if (pos[0] == end[0] && pos[1] == end[1]) { // return the path that led to the find return [path.concat([end]), speedTotal] } if (pos[0] < 0 || pos[0] >= matrix.length || pos[1] < 0 || pos[1] >= matrix[0].length || matrix[pos[0]][pos[1]].classList.contains('visitedCell') || matrix[pos[0]][pos[1]].classList.contains('selectedCell')) { continue; } matrix[pos[0]][pos[1]].classList.add('visitedCell'); highlightCurNode(matrix[pos[0]][pos[1]], speedTotal); speedTotal += +speed; highlightSearching(matrix[pos[0]][pos[1]], speedTotal); speedTotal += +speed; for (let i = 0; i < direction.length; i++) { // Perform this check first: // extend and push the path on the stack stack.push(path.concat([direction[i]])); } } return [null, speedTotal] } function highlightSearching(cell, speed) { if (cell.classList.contains('startNode') || cell.classList.contains('endNode')) return; setTimeout(() => { cell.classList.add('highlightSearching'); cell.classList.remove('curNode'); }, speed); } function highlightCurNode(cell, speed) { if (cell.classList.contains('startNode') || cell.classList.contains('endNode')) return; setTimeout(() => cell.classList.add('curNode') , speed); }
5b5acf34d10906d4c57692b68e3199b2432bfe54
[ "JavaScript", "Markdown" ]
3
JavaScript
lennonchoong/Pathfinder-Algorithm-Visualizer
80c15c6e3c43763d90db20191230bc1ae0e4b94d
62186e2e90ac8167c4b616baf6fa9ee75146a37e
refs/heads/master
<file_sep>#Importing libraries. library(ggplot2) library(reshape2) library(forecast) library(zoo) library(Metrics) library(caret) library(GGally) #Loading datasets provided by Kaggle. We won't include the 'stores' dataset since we're not attempting to forecasting at the store level. #The training data. This is a large file. Workstation has 32gb ram. train = read.csv('C:/Users/smith/Desktop/CKME 136/Grocery Sales Forecasting/train.csv', header = T, sep = ',') dim(train) memory.size() memory.limit() #The item attributes table. items = read.csv('C:/Users/smith/Desktop/CKME 136/Grocery Sales Forecasting/items.csv', header = T, sep = ',') #Transaction counts by location. We aggregate this data to the forecasting level. transactions = read.csv('C:/Users/smith/Desktop/CKME 136/Grocery Sales Forecasting/transactions.csv', header = T, sep = ',') transactions_agg_sum <- aggregate(transactions$transactions, by = list(transactions$date), sum) names(transactions_agg_sum)[1] <- 'date' names(transactions_agg_sum)[2] <- 'transactions' rm(transactions) #Holiday and event details by day. holidays_events = read.csv('C:/Users/smith/Desktop/CKME 136/Grocery Sales Forecasting/holidays_events.csv', header = T, sep = ',') #Based on the data description from Kaggle, some days have duplicate entries for holidays since some holidays were transferred to other dates. #Remove duplicate dates where holidays were transferred/bridged and where different levels of gov't celebrate. holidays_events = holidays_events[!duplicated(holidays_events$date),] #Daily oil price. oil = read.csv('C:/Users/smith/Desktop/CKME 136/Grocery Sales Forecasting/oil.csv', header = T, sep = ',') #Training data preprocessing. #Drop Kaggle row ID. train$id <- NULL #We'll be aggregating store sales for each SKU. #Regarding the onpromotion attribute at the aggregate level for each SKU, we'll accept 'True' if it were 'True' at any store on a given day. #Assuming missing data is 'False'. train$onpromotion[train$onpromotion == ""] <- "False" #Aggregate function 'max' only works on numeric values. train$onpromotion <- as.integer(train$onpromotion) train$onpromotion[train$onpromotion == 2] <- 0 train$onpromotion[train$onpromotion == 3] <- 1 #Aggregating store level sales by SKU for 'unit_sales' and 'onpromotion'. train_agg_sum <- aggregate(train$unit_sales, by = list(train$date, train$item_nbr), sum) #Restoring column names. names(train_agg_sum)[1] <- 'date' names(train_agg_sum)[2] <- 'item_nbr' names(train_agg_sum)[3] <- 'unit_sales' train_agg_max <- aggregate(train$onpromotion, by = list(train$date, train$item_nbr), max) names(train_agg_max)[1] <- 'date' names(train_agg_max)[2] <- 'item_nbr' names(train_agg_max)[3] <- 'onpromotion' #Joining aggregated 'unit_sales' and 'onpromotion' dataframes. rm(train) train_agg <- merge(x = train_agg_sum, y = train_agg_max, by.x = c('date', 'item_nbr'), all.x = T) rm(train_agg_sum) rm(train_agg_max) #Creating week, year, weekday, and year-week attributes since we're aggregating to the week level and some further preprocessing will be required. train_agg$date <- as.Date(train_agg$date, format = "%Y-%m-%d") train_agg$week <- strftime(as.character(train_agg$date), "%U") unique(train_agg$week) train_agg$year <- strftime(as.character(train_agg$date), "%Y") unique(train_agg$year) train_agg$weekday <- strftime(as.character(train_agg$date), "%A") unique(train_agg$weekday) #This will be used for time series forecasting later. train_agg$yearweek <- as.Date(paste(train_agg$year, train_agg$week, "06", sep = '-'), format = "%Y-%U-%w") unique(train_agg$week[is.na(train_agg$yearweek)]) unique(train_agg$year[is.na(train_agg$yearweek)]) train_agg$yearweek[is.na(train_agg$yearweek) & train_agg$year == '2013'] <- "2013-01-01" train_agg$yearweek[is.na(train_agg$yearweek) & train_agg$year == '2014'] <- "2014-01-01" train_agg$yearweek[is.na(train_agg$yearweek) & train_agg$year == '2015'] <- "2015-01-01" train_agg$yearweek[is.na(train_agg$yearweek) & train_agg$year == '2016'] <- "2016-01-01" #We'll now join the other datasets to create a 'spine' for the final dataset and begin imputing on missing values. #We'll eventually aggregate again to weekly level and rejoin the other tables. #Converting date back to factor for joining. train_agg$date <- as.factor(train_agg$date) data = merge(x = train_agg, y = items, by = 'item_nbr', all.x = T) data = merge(x = data, y = transactions_agg_sum, by.x = 'date', all.x = T) data = merge(x = data, y = oil, by.x = 'date', all.x = T) data = merge(x = data, y = holidays_events, by = 'date', all.x = T) rm(train_agg) rm(transactions_agg_sum) rm(holidays_events) rm(oil) #Now to fix missing values using imputation. #identifying columns with NA's colSums(is.na(data)) #We'll work on the 'transactions' attribute first. #Identify weekdays, weeks, and years with NA's. unique(data[is.na(data$transactions),]$date) unique(data[is.na(data$transactions),]$weekday) #Replace missing values with average values of the same weekday for other weeks in the same year. data[which(is.na(data$transactions) & data$date == "2016-01-01"),]$transactions <- mean(data[which(data$weekday == "Friday" & data$year == "2016"),]$transactions, na.rm = T) data[which(is.na(data$transactions) & data$date == "2016-01-03"),]$transactions <- mean(data[which(data$weekday == "Sunday" & data$year == "2016"),]$transactions, na.rm = T) #Now for the 'dcoilwtico' attribute. Replace values for missing days with the value of the previous day. data$dcoilwtico <- na.locf(data$dcoilwtico, fromLast = T) #For the holiday attributes, we'll replace each day without a holiday as "No Holiday". #Since variables are factors, add new level "No Holiday". levels(data$type) <- c(levels(data$type), "No Holiday") data$type[is.na(data$type)] <- 'No Holiday' levels(data$locale) <- c(levels(data$locale), "No Holiday") data$locale[is.na(data$locale)] <- 'No Holiday' levels(data$locale_name) <- c(levels(data$locale_name), "No Holiday") data$locale_name[is.na(data$locale_name)] <- 'No Holiday' levels(data$description) <- c(levels(data$description), "No Holiday") data$description[is.na(data$description)] <- 'No Holiday' levels(data$transferred) <- c(levels(data$transferred), "No Holiday") data$transferred[is.na(data$transferred)] <- 'No Holiday' #To keep things simple, we'll create a dummy variable for holiday/no holiday data$holiday <- 0 #Based on Kaggle data description the following holiday attribute values are actual holidays. data$holiday[which(data$type == 'Transfer' | data$type == 'Bridge' | data$type == 'Holiday' | data$type == 'Additional' | data$type == 'Event')] <- 1 #Now aggregating to the week level. #We aggregated daily store level sales to week in two steps because of resource constrains. data.wk.sales <- aggregate(data$unit_sales, by = list(data$year, data$week, data$yearweek, data$item_nbr), sum) data.wk.onpromotion <- aggregate(data$onpromotion, by = list(data$year, data$week, data$yearweek, data$item_nbr), max) names(data.wk.sales) <- c('year', 'week', 'yearweek', 'item_nbr', 'unit_sales') names(data.wk.onpromotion) <- c('year', 'week', 'yearweek', 'item_nbr', 'onpromotion') data.wk <- merge(x = data.wk.sales, y = data.wk.onpromotion, by.x = c('year', 'week', 'yearweek', 'item_nbr'), all.x = T) rm(data.wk.sales) rm(data.wk.onpromotion) #Next aggregate and join other attributes to new weekly dataset. #Starting with transactions. data.wk.txns <- aggregate(data$transactions, by = list(data$date), mean) names(data.wk.txns)[1] <- 'date' names(data.wk.txns)[2] <- 'transactions' data.wk.txns$date <- as.Date(data.wk.txns$date, format = "%Y-%m-%d") data.wk.txns$week <- strftime(as.character(data.wk.txns$date), "%U") data.wk.txns$year <- strftime(as.character(data.wk.txns$date), "%Y") data.wk.txns <- aggregate(data.wk.txns$transactions, by = list(data.wk.txns$year, data.wk.txns$week), sum) names(data.wk.txns)[1] <- 'year' names(data.wk.txns)[2] <- 'week' names(data.wk.txns)[3] <- 'transactions' #Next oil. data.wk.oil <- aggregate(data$dcoilwtico, by = list(data$year, data$week), mean) names(data.wk.oil)[1] <- 'year' names(data.wk.oil)[2] <- 'week' names(data.wk.oil)[3] <- 'oil' #Next holidays. data.wk.holiday <-aggregate(data$holiday, by = list(data$year, data$week), max) names(data.wk.holiday)[1] <- 'year' names(data.wk.holiday)[2] <- 'week' names(data.wk.holiday)[3] <- 'holiday' #Joining data together into dataset for algorithm training/testing. data.wk.ml = merge(x = data.wk, y = items, by = 'item_nbr', all.x = T) data.wk.ml = merge(x = data.wk.ml, y = data.wk.txns, by = c("year", "week"), all.x = T) data.wk.ml = merge(x = data.wk.ml, y = data.wk.oil, by = c('year', 'week') , all.x = T) data.wk.ml = merge(x = data.wk.ml, y = data.wk.holiday, by = c('year', 'week'), all.x = T) #Visualization str(data.wk.ml) summary(data.wk.ml) #Initializing ggplot object with data frame. g <- ggplot(data.wk.ml) #Examining sales trend over time. g + geom_col(aes(x = year, y = unit_sales)) + ggtitle("Total Unit Sales") #Number of weeks in each year. ggplot(setNames(aggregate(data.wk.ml$week, by = list(data.wk.ml$year), function(x) length(unique(x))), c("year", "Num.weeks"))) + geom_col(aes(x = year, y = Num.weeks)) + labs(title = "Number of Weeks", x = "Year", y = "Weeks") + geom_text(aes(x = year, y = Num.weeks, label = Num.weeks), nudge_y = 2) + theme(axis.title.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank()) #Unit sales by week. g + geom_col(aes(x = week, y = unit_sales)) + ggtitle("Weekly Unit Sales") #Weekly Unit Sales by Year. ggplot(setNames(aggregate(data.wk.ml$unit_sales, by = list(data.wk.ml$yearweek), sum), c("year.week", "unit_sales"))) + geom_line(aes(x = year.week, y = unit_sales)) + labs(title = "Weekly Unit Sales Trend", x = "Time (weeks)", y = "Unit Sales") #Weekly transactions by Year. g + geom_line(aes(x = yearweek, y = transactions)) + labs(title = "Weekly Transactions Trend", x = "Time (weeks)", y = "Transactions") #Weekly average oil price. g + geom_line(aes(x = yearweek, y = oil)) + labs(title = "Weekly Average Oil Price Trend", x = "Time (weeks)", y = "Oil Price") #Scatterplot between oil price and unit sales. g + geom_point(aes(x = unit_sales, y = oil)) + labs(title = "Oil Price vs. Unit Sales", x = "Unit Sales", y = "Oil Price") #Scatterplot between oil price and transactions. g + geom_point(aes(x = transactions, y = oil)) + labs(title = "Weekly Average Oil Price vs. Weekly Total Transactions", x = "Transactions", y = "Oil Price") #Boxplot of Unit Sales by promotion attribute. ggplot(data.wk.ml, aes(x = onpromotion, y = unit_sales), group = 1) + geom_boxplot() + labs(title = "Unit Sales: Promotion vs None", x = "Promotion", y = "Unit Sales") #Item counts by product family. ggplot(items) + geom_bar(aes(x = family, fill = family), stat = 'count') + theme(axis.text.x = element_text(angle = 90, hjust = 1), legend.position="none") + labs(title = "Item Counts by Product Family", x = "Family", y = "Count") #Unit sales by product family g + geom_boxplot(aes(x = family, y = unit_sales)) + theme(axis.text.x = element_text(angle = 90, hjust = 1), legend.position="none") + labs(title = "Unit Sales by Product Family", x = "Family", y = "Unit Sales") #Average unit sales by product family ggplot(setNames(aggregate(data.wk.ml$unit_sales, by = list(data.wk.ml$family), mean), c("family", "unit_sales"))) + geom_col(aes(x = family, y = unit_sales)) + theme(axis.text.x = element_text(angle = 90, hjust = 1), legend.position="none") + labs(title = "Average Unit Sales by Product Family", x = "Family", y = "Average Unit Sales") #Row Counts by 'perishable' ggplot(items) + geom_bar(aes(x = perishable), stat = 'count') + theme(axis.text.x = element_text(angle = 90, hjust = 1), legend.position="none") + labs(title = "'Perishable' Counts", x = "Perishable", y = "Count") #Average Unit Sales by Perishable. ggplot(setNames(aggregate(data.wk.ml$unit_sales, by = list(data.wk.ml$perishable), mean), c("perishable", "unit_sales"))) + geom_col(aes(x = perishable, y = unit_sales)) + theme(axis.text.x = element_text(angle = 90, hjust = 1), legend.position="none") + labs(title = "Average Unit Sales by 'perishable'", x = "Perishable", y = "Average Unit Sales") #Average Unit Sales by Holiday. ggplot(setNames(aggregate(data.wk.ml$unit_sales, by = list(data.wk.ml$holiday), mean), c("holiday", "unit_sales")))+ geom_col(aes(x = holiday, y = unit_sales)) + theme(axis.text.x = element_text(angle = 90, hjust = 1), legend.position="none") + labs(title = "Average Unit Sales by 'holiday'", x = "Holiday", y = "Average Unit Sales") #Scatterplot matrix on numeric data. ggpairs(data.wk.ml[,c(1,5,6,9,10,11,12)]) pairs(data.wk.ml[,c(5,10,11)]) cor(data.wk.ml[,c(5,10,11)]) #Cast variables. data.wk.ml$year <- as.factor(data.wk.ml$year) data.wk.ml$week <- as.factor(data.wk.ml$week) data.wk.ml$item_nbr <- as.factor(data.wk.ml$item_nbr) data.wk.ml$onpromotion <- as.factor(data.wk.ml$onpromotion) data.wk.ml$class <- as.factor(data.wk.ml$class) data.wk.ml$perishable <- as.factor(data.wk.ml$perishable) data.wk.ml$holiday <- as.factor(data.wk.ml$holiday) #Preparing data for time series forecasting. #Transforming dataset to rows = sales time series and columns SKUs. data.wk.fcst <- dcast(data.wk.ml, year + week + yearweek ~ item_nbr, value.var = "unit_sales") #make 2017 testing data. Split training and testing data. data.wk.fcst.train <- data.wk.fcst[which(data.wk.fcst$year == '2013' | data.wk.fcst$year == '2014' | data.wk.fcst$year == '2015' | data.wk.fcst$year == '2016'),] data.wk.fcst.test <- data.wk.fcst[data.wk.fcst$year == '2017',] #Removing SKUs with any NA's- weeks with 0 sales. SKU.NA <- colnames(data.wk.fcst[-(1:3)]) NA.CNT <- unname(apply(data.wk.fcst[-(1:3)], 2, function(x) sum(is.na(x)))) SKU.NA <- cbind.data.frame(SKU.NA, NA.CNT) SKU.NA$NA.CNT <- as.integer(SKU.NA$NA.CNT) SKU.list <- SKU.NA$SKU.NA[SKU.NA$NA.CNT == 0] #Creating a random sample of 53 SKUs since Random Forest class cannot handle factors with more than 53 levels. This random selection of the core SKU group will be the basis for our model comparison. set.seed(5) SKU.list53 <- sample(SKU.list, 53) #Limiting datasets to sample SKUs. data.wk.fcst.train <- data.wk.fcst.train[names(data.wk.fcst.train) %in% SKU.list53] #data.wk.fcst.train$year <- data.wk.fcst$year[data.wk.fcst$year != '2017'] #data.wk.fcst.train$week <- data.wk.fcst$week[data.wk.fcst$year != '2017'] #data.wk.fcst.train$yearweek <- data.wk.fcst$yearweek[data.wk.fcst$year != '2017'] #include year, week, and yearweek. data.wk.fcst.test <- data.wk.fcst.test[names(data.wk.fcst.test) %in% SKU.list53] data.wk.fcst.test$year <- data.wk.fcst$year[data.wk.fcst$year == '2017'] data.wk.fcst.test$week <- data.wk.fcst$week[data.wk.fcst$year == '2017'] data.wk.fcst.test$yearweek <- data.wk.fcst$yearweek[data.wk.fcst$year == '2017'] #Fitting arima model. fcst.arima <- ts(data.wk.fcst.train, frequency = 53, start = c(2013,1)) fit.arima <- apply (fcst.arima, 2, auto.arima) pred.arima <- lapply(fit.arima, forecast, 33) pred.arima <- sapply(pred.arima, "[", 4) pred.arima <- as.data.frame(pred.arima) #Unit Sales for selected SKUs. autoplot(fcst.arima) + theme(axis.text.x = element_text(angle = 90, hjust = 1), legend.position="none") + labs(title = "Unit Sales by SKU", x = "Time (week)", y = "Unit Sales") #Arranging and combining results with actuals for scoring. the melt function transforms the pivoted data back to tabular format. data.wk.fcst.sales <- melt(data.wk.fcst.test, id.vars = c("year", "week", "yearweek"), variable.name = "item_nbr", value.name = "unit_sales") data.wk.fcst.pred <- data.wk.fcst.sales[,1:3] data.wk.fcst.arima <- melt(pred.arima, variable.name = "item_nbr", value.name = "unit_sales_pred") data.wk.fcst.test.arima <- cbind.data.frame(data.wk.fcst.sales, unit_sales_pred = data.wk.fcst.arima[,2]) #Scoring using the root mean squared error (RMSE). rmse(as.vector(data.wk.fcst.test.arima$unit_sales), as.vector(data.wk.fcst.test.arima$unit_sales_pred)) #Plotting the prediction vs. actuals. ggplot(data.wk.fcst.test.arima) + geom_point(aes(x = unit_sales, y = unit_sales_pred)) + geom_abline(intercept = 0, slope = 1) + labs(title = "predicted vs actual - ARIMA - 53 core SKUs", x = "actual", y = "predicted") #Fitting ets model. fcst.ets <- ts(data.wk.fcst.train, frequency = 53, start = c(2013,1)) fit.ets <- apply (fcst.ets, 2, ets) pred.ets <- lapply(fit.ets, forecast, 33) pred.ets <- sapply(pred.ets, "[", 2) pred.ets <- as.data.frame(pred.ets) #Arranging and combining results with actuals for scoring. the melt function transforms the pivoted data back to tabular format. data.wk.fcst.sales <- melt(data.wk.fcst.test, id.vars = c("year", "week", "yearweek"), variable.name = "item_nbr", value.name = "unit_sales") data.wk.fcst.pred <- data.wk.fcst.sales[,1:3] data.wk.fcst.ets <- melt(pred.ets, variable.name = "item_nbr", value.name = "unit_sales_pred") data.wk.fcst.test.ets <- cbind.data.frame(data.wk.fcst.sales, unit_sales_pred = data.wk.fcst.ets[,2]) rmse(as.vector(data.wk.fcst.test.ets$unit_sales), as.vector(data.wk.fcst.test.ets$unit_sales_pred)) ggplot(data.wk.fcst.test.ets) + geom_point(aes(x = unit_sales, y = unit_sales_pred)) + geom_abline(intercept = 0, slope = 1) + labs(title = "predicted vs actual - ETS - 53 core SKUs", x = "actual", y = "predicted") #Mean of current year model (baseline). data.wk.fcst.train.mean <- as.data.frame(apply(data.wk.fcst.train[160:212,], 2, mean)) data.wk.fcst.train.mean <- t(data.wk.fcst.train.mean) rownames(data.wk.fcst.train.mean) <- c() data.wk.fcst.test.mean <- as.data.frame(apply(data.wk.fcst.train.mean, 2, function(x) rep(x, 33))) data.wk.fcst.test.mean <- melt(data.wk.fcst.test.mean, variable.name = "item_nbr", value.name = "unit_sales_pred") data.wk.fcst.test.mean <- cbind.data.frame(data.wk.fcst.sales, unit_sales_pred = data.wk.fcst.test.mean[,2]) rmse(as.vector(data.wk.fcst.test.mean$unit_sales), as.vector(data.wk.fcst.test.mean$unit_sales_pred)) ggplot(data.wk.fcst.test.mean) + geom_point(aes(x = unit_sales, y = unit_sales_pred)) + geom_abline(intercept = 0, slope = 1) + labs(title = "predicted vs actual - MEAN - 53 core SKUs", x = "actual", y = "predicted") #split train/test. data.wk.ml.train <- data.wk.ml[which(data.wk.ml$year != '2017' & data.wk.ml$item_nbr %in% SKU.list53),] data.wk.ml.train$yearweek <- NULL data.wk.ml.test <- data.wk.ml[which(data.wk.ml$year == '2017'& data.wk.ml$item_nbr %in% SKU.list53),] data.wk.ml.test$yearweek <- NULL #To plot boxplot of SKUs. data.wk.ml.core <- data.wk.ml[data.wk.ml$item_nbr %in% SKU.list53,] ggplot(data.wk.ml.core) + geom_boxplot(aes(x = item_nbr, y = unit_sales)) + theme(axis.text.x = element_text(angle = 90, hjust = 1), legend.position="none") + labs(title = "Unit Sales by SKU", x = "SKU", y = "Unit Sales") #Recast levels for similarity between training and testing datasets. data.wk.ml.train$year <- as.integer(data.wk.ml.train$year) data.wk.ml.test$year <- as.integer(data.wk.ml.test$year) data.wk.ml.train$onpromotion <- as.factor(data.wk.ml.train$onpromotion) data.wk.ml.train$perishable <- as.factor(data.wk.ml.train$perishable) data.wk.ml.train$holiday <- as.factor(data.wk.ml.train$holiday) data.wk.ml.train$item_nbr <- factor(data.wk.ml.train$item_nbr) data.wk.ml.train$family <- factor(data.wk.ml.train$family) data.wk.ml.train$class <- factor(data.wk.ml.train$class) data.wk.ml.train$week <- factor(data.wk.ml.train$week) data.wk.ml.test$onpromotion <- as.factor(data.wk.ml.test$onpromotion) data.wk.ml.test$perishable <- as.factor(data.wk.ml.test$perishable) data.wk.ml.test$holiday <- as.factor(data.wk.ml.test$holiday) data.wk.ml.test$item_nbr <- factor(data.wk.ml.test$item_nbr) data.wk.ml.test$family <- factor(data.wk.ml.test$family) data.wk.ml.test$class <- factor(data.wk.ml.test$class) data.wk.ml.test$week <- factor(data.wk.ml.test$week) levels(data.wk.ml.test$onpromotion) <- levels(data.wk.ml.train$onpromotion) levels(data.wk.ml.test$perishable) <- levels(data.wk.ml.train$perishable) levels(data.wk.ml.test$holiday) <- levels(data.wk.ml.train$holiday) levels(data.wk.ml.test$item_nbr) <- levels(data.wk.ml.train$item_nbr) levels(data.wk.ml.test$family) <- levels(data.wk.ml.train$family) levels(data.wk.ml.test$class) <- levels(data.wk.ml.train$class) levels(data.wk.ml.test$week) <- levels(data.wk.ml.train$week) #One-hot encoding. dmy <- dummyVars("~.", data = data.wk.ml.train) data.wk.ml.train.dmy <- data.frame(predict(dmy, newdata = data.wk.ml.train)) dmy <- dummyVars("~.", data = data.wk.ml.test) data.wk.ml.test.dmy <- data.frame(predict(dmy, newdata = data.wk.ml.test)) #Fitting and scoring various machine learning algorithms. #Linear regression. ml.lm.fit <-train(x = data.wk.ml.train[,-4], y = data.wk.ml.train$unit_sales, method = 'lm', trControl = trainControl(method = "none", number = 1, repeats = 1)) ml.lm.pred <- predict.train(object=ml.lm.fit,data.wk.ml.test[,-4],type="raw") df.ml.lm.pred <- cbind.data.frame(data.wk.fcst.test.mean[1:5], unit_sales_pred = ml.lm.pred) #Model diagnostics summary(ml.lm.fit) #Plotting residuals ml.lm.pred.resid <- resid(ml.lm.fit) df.ml.lm.pred.resid <- cbind.data.frame(data.wk.ml.train, resid = ml.lm.pred.resid) ggplot(df.ml.lm.pred.resid) + geom_point(aes(x = unit_sales, y = ml.lm.pred.resid)) + geom_abline(intercept = 0, slope = 0) + labs(title = "Linear Regression Residual Plot", x = "actual", y = "predicted") #Heavy autocorrelation #Visualizing variable importance ImpMeasure<-data.frame(varImp(ml.lm.fit)$importance) ImpMeasure$Vars<-row.names(ImpMeasure) rownames(ImpMeasure) <- c() ggplot(ImpMeasure[order(-ImpMeasure$Overall),][1:20,]) + geom_point(aes(y = Vars, x = Overall)) rmse(as.vector(data.wk.ml.test$unit_sales), as.vector(ml.lm.pred)) ggplot(df.ml.lm.pred) + geom_point(aes(x = unit_sales, y = unit_sales_pred)) + geom_abline(intercept = 0, slope = 1) + labs(title = "predicted vs actual - LINEAR REGRESSION - 53 core SKUs", x = "actual", y = "predicted") #Random Forest regressor. ml.rf.fit <-train(x = data.wk.ml.train[,-4], y = data.wk.ml.train$unit_sales, method = 'rf', trControl = trainControl(method = "none", number = 1, repeats = 1)) ml.rf.pred <- predict.train(object=ml.rf.fit,data.wk.ml.test[,-4],type="raw") df.ml.rf.pred <- cbind.data.frame(data.wk.fcst.test.mean[1:5], unit_sales_pred = ml.rf.pred) rmse(as.vector(data.wk.ml.test$unit_sales), as.vector(ml.rf.pred)) ggplot(df.ml.rf.pred) + geom_point(aes(x = unit_sales, y = unit_sales_pred)) + geom_abline(intercept = 0, slope = 1) + labs(title = "predicted vs actual - RANDOM FOREST - 53 core SKUs", x = "actual", y = "predicted") #Knn regressor. ml.knn.fit <-train(x = data.wk.ml.train.dmy[,!names(data.wk.ml.train.dmy) == "unit_sales"], y = data.wk.ml.train.dmy$unit_sales, method = 'knn', trControl = trainControl(method = "none", number = 1, repeats = 1)) ml.knn.pred <- predict.train(object=ml.knn.fit, data.wk.ml.test.dmy[!names(data.wk.ml.test.dmy) == "unit_sales"],type="raw") df.ml.knn.pred <- cbind.data.frame(data.wk.fcst.test.mean[1:5], unit_sales_pred = ml.knn.pred) rmse(as.vector(data.wk.ml.test$unit_sales), as.vector(ml.knn.pred)) ggplot(df.ml.knn.pred) + geom_point(aes(x = unit_sales, y = unit_sales_pred)) + geom_abline(intercept = 0, slope = 1) + labs(title = "predicted vs actual - KNN - 53 core SKUs", x = "actual", y = "predicted") #Gradient boosting machine regressor. ml.gbm.fit <-train(x = data.wk.ml.train[,-4], y = data.wk.ml.train$unit_sales, method = 'gbm', trControl = trainControl(method = "none", number = 1, repeats = 1)) ml.gbm.pred <- predict.train(object=ml.gbm.fit,data.wk.ml.test[,-4],type="raw") df.ml.gbm.pred <- cbind.data.frame(data.wk.fcst.test.mean[1:5], unit_sales_pred = ml.gbm.pred) rmse(as.vector(data.wk.ml.test$unit_sales), as.vector(ml.gbm.pred)) ggplot(df.ml.gbm.pred) + geom_point(aes(x = unit_sales, y = unit_sales_pred)) + geom_abline(intercept = 0, slope = 1) + labs(title = "predicted vs actual - GBM - 53 core SKUs", x = "actual", y = "predicted") #Neural network regressor. ml.nnet.fit <-train(x = data.wk.ml.train.dmy[,!names(data.wk.ml.train.dmy) == "unit_sales"], y = data.wk.ml.train.dmy$unit_sales, method = 'brnn', trControl = trainControl(method = "none", number = 1, repeats = 1)) ml.nnet.pred <- predict.train(object=ml.nnet.fit,data.wk.ml.test.dmy[!names(data.wk.ml.test.dmy) == "unit_sales"],type="raw") df.ml.nnet.pred <- cbind.data.frame(data.wk.fcst.test.mean[1:5], unit_sales_pred = ml.nnet.pred) rmse(as.vector(data.wk.ml.test$unit_sales), as.vector(ml.nnet.pred)) ggplot(df.ml.nnet.pred) + geom_point(aes(x = unit_sales, y = unit_sales_pred)) + geom_abline(intercept = 0, slope = 1) + labs(title = "predicted vs actual - BAYESIAN NEURAL NETWORK - 53 core SKUs", x = "actual", y = "predicted") #Bagged decision tree regressor. ml.treebag.fit <-train(x = data.wk.ml.train.dmy[,!names(data.wk.ml.train.dmy) == "unit_sales"], y = data.wk.ml.train.dmy$unit_sales, method = 'treebag', trControl = trainControl(method = "none", number = 1, repeats = 1)) ml.treebag.pred <- predict.train(object=ml.treebag.fit,data.wk.ml.test.dmy[!names(data.wk.ml.test.dmy) == "unit_sales"],type="raw") df.ml.treebag.pred <- cbind.data.frame(data.wk.fcst.test.mean[1:5], unit_sales_pred = ml.treebag.pred) rmse(as.vector(data.wk.ml.test$unit_sales), as.vector(ml.treebag.pred)) ggplot(df.ml.treebag.pred) + geom_point(aes(x = unit_sales, y = unit_sales_pred)) + geom_abline(intercept = 0, slope = 1) + labs(title = "predicted vs actual - BAGGED DECISION TREE - 53 core SKUs", x = "actual", y = "predicted") #XGBoost regressor. ml.xgbLinear.fit <-train(x = data.wk.ml.train.dmy[,!names(data.wk.ml.train.dmy) == "unit_sales"], y = data.wk.ml.train.dmy$unit_sales, method = 'xgbLinear', trControl = trainControl(method = "none", number = 1, repeats = 1)) ml.xgbLinear.pred <- predict.train(object=ml.xgbLinear.fit, data.wk.ml.test.dmy[!names(data.wk.ml.test.dmy) == "unit_sales"],type="raw") df.ml.xgbLinear.pred <- cbind.data.frame(data.wk.fcst.test.mean[1:5], unit_sales_pred = ml.xgbLinear.pred) rmse(as.vector(data.wk.ml.test.dmy$unit_sales), as.vector(ml.xgbLinear.pred)) ggplot(df.ml.xgbLinear.pred) + geom_point(aes(x = unit_sales, y = unit_sales_pred)) + geom_abline(intercept = 0, slope = 1) + labs(title = "predicted vs actual - XGBOOST - 53 core SKUs", x = "actual", y = "predicted") #Support vector machines regressor. ml.svmLinear.fit <-train(x = data.wk.ml.train.dmy[,!names(data.wk.ml.train.dmy) == "unit_sales"], y = data.wk.ml.train.dmy$unit_sales, method = 'svmLinear', trControl = trainControl(method = "none", number = 1, repeats = 1)) ml.svmLinear.pred <- predict.train(object=ml.svmLinear.fit, data.wk.ml.test.dmy[!names(data.wk.ml.test.dmy) == "unit_sales"],type="raw") df.ml.svmLinear.pred <- cbind.data.frame(data.wk.fcst.test.mean[1:5], unit_sales_pred = ml.svmLinear.pred) rmse(as.vector(data.wk.ml.test.dmy$unit_sales), as.vector(ml.svmLinear.pred)) ggplot(df.ml.svmLinear.pred) + geom_point(aes(x = unit_sales, y = unit_sales_pred)) + geom_abline(intercept = 0, slope = 1) + labs(title = "predicted vs actual - SVM - 53 core SKUs", x = "actual", y = "predicted") <file_sep># CKME-136 Capstone Project: Forecasting Grocery Sales
559f23ae0ab73acd2e9e67601fb7ee3b1620994f
[ "Markdown", "R" ]
2
R
macsmith26/CKME-136
8f596520aea82aafe32fef0712ce004290ffbbcd
23a7dffc7e2d31d7253cd59677fcdb8ab8f3a516
refs/heads/master
<repo_name>timothyjlaurent/IMG-Mirror<file_sep>/code/Sfam_updater/createGeneTable.sql genes | CREATE TABLE `genes` ( `gene_oid` int(10) unsigned NOT NULL AUTO_INCREMENT, `taxon_oid` bigint(20) unsigned NOT NULL, `protein_id` varchar(15) DEFAULT NULL, `type` varchar(64) NOT NULL, `start` int(10) unsigned NOT NULL, `end` int(10) unsigned NOT NULL, `strand` enum('-1','0','1') NOT NULL, `locus` varchar(30) NOT NULL, `name` varchar(100) DEFAULT NULL, `description` varchar(1000) NOT NULL, `dna` text NOT NULL, `protein` text, `scaffold_name` varchar(30) NOT NULL, `scaffold_id` varchar(15) NOT NULL, PRIMARY KEY (`gene_oid`), KEY `genomes` (`taxon_oid`), KEY `protein_id` (`protein_id`), KEY `name` (`name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 <file_sep>/code/Sfam_updater/createGenomeTable.sql CREATE TABLE `genomes` ( `taxon_oid` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `ncbi_taxon_id` int(10) unsigned NOT NULL, `ncbi_project_id` int(10) unsigned NOT NULL, `completion` enum('Draft','Finished','Permanent Draft') NOT NULL, `domain` enum('Bacteria','Archaea','Eukaryota') NOT NULL, `name` varchar(256) NOT NULL, `directory` varchar(100) NOT NULL, `phylum` varchar(25) NOT NULL, `class` varchar(30) NOT NULL, `order` varchar(30) NOT NULL, `family` varchar(50) NOT NULL, `genus` varchar(50) NOT NULL, `sequencing_center` text NOT NULL, `gene_count` int(10) NOT NULL, `genome_size` int(25) NOT NULL, `scaffold_count` int(10) NOT NULL, `img_release` varchar(15) NOT NULL, `add_date` varchar(15) NOT NULL, `is_public` enum('Yes','No') NOT NULL, `gc` decimal(3,1) DEFAULT NULL, `gram_stain` enum('+','-') DEFAULT NULL, `shape` text, `arrangement` text, `endospores` text, `motility` text, `salinity` text, `oxygen_req` text, `habitat` text, `temp_range` text, `pathogenic_in` text, `disease` text, PRIMARY KEY (`taxon_oid`), KEY `ncbi_taxon_id` (`ncbi_taxon_id`), KEY `taxon_oid` (`taxon_oid`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1
41cd3d64148aafcd99019bd155f4c1c61db88e96
[ "SQL" ]
2
SQL
timothyjlaurent/IMG-Mirror
33651fbcf670366e292bf25eba5f3c4a92a6ab7c
4b759c962619c8874653d1f58663c5df47133c75
refs/heads/master
<repo_name>daviaugustos/react-native-tools-sample<file_sep>/src/config/root-reducer.js import { combineReducers } from 'redux' import reduxExamplesReducer from '../containers/Redux-Examples/reduxExamples.reducer' const rootReducer = combineReducers({ reduxExamplesReducer }) export default rootReducer<file_sep>/src/containers/Redux-Examples/reduxExamples.index.js import React, { Component } from 'react'; import { TouchableHighlight, View, Text, StyleSheet, Button } from 'react-native'; import { connect } from 'react-redux' import { fetchData } from './reduxExamples.actions' let styles const App = class ReduxExamples extends Component { constructor(props) { super(props); this.state = { counter: 0 }; } onPress = () => { this.setState({ counter: this.state.counter + 1 }); } render() { return ( <View id="xD" style={styles.container} accessibilityLabel="testview"> <Text style={styles.text}>End to End Testing Sample</Text> <Text style={styles.text} accessibilityLabel="counter">Counter: {this.state.counter}</Text> <Button onPress={this.onPress} title="Press me" accessibilityLabel="button" /> <View style={styles.reduxSagaView}> <Text style={styles.text}>Redux Saga Example</Text> <TouchableHighlight style={styles.button} onPress={() => this.props.fetchData()}> <Text style={styles.buttonText}>Load Data</Text> </TouchableHighlight> <View style={styles.mainContent}> { this.props.reduxExamplesReducer.isFetching && <Text>Loading</Text> } { this.props.reduxExamplesReducer.data.length ? ( this.props.reduxExamplesReducer.data.map((person, i) => { return <View key={i} > <Text>Name: {person.name}</Text> <Text>Age: {person.age}</Text> </View> }) ) : null } </View> </View> </View> ) } } styles = StyleSheet.create({ container: { marginTop: 100 }, text: { textAlign: 'center', padding: 10 }, button: { height: 60, margin: 10, justifyContent: 'center', alignItems: 'center', backgroundColor: '#0b7eff' }, buttonText: { color: 'white' }, mainContent: { margin: 10 }, reduxSagaView: { marginTop: 50 } }) function mapStateToProps (state) { return { reduxExamplesReducer: state.reduxExamplesReducer } } const mapActionsToProps = { fetchData: fetchData } export default connect( mapStateToProps, mapActionsToProps )(App)
10e2a92a841b5cb78ecd8b5a9b75602e26d6b24d
[ "JavaScript" ]
2
JavaScript
daviaugustos/react-native-tools-sample
fd96b7fce79a7fe748e44decac74948384a85e5c
71f955b2bf90b3a3b67e3543039f43baaf0a3083
refs/heads/master
<repo_name>joseLucas-code/Music-Player-WEB<file_sep>/js/main.js const playerContainer = document.querySelector('.player-container') const artistiIMG = document.querySelector('.album-content img') const songTittle = document.querySelector('.album-content h2') const artistName = document.querySelector('.album-content p') const prevBTN = document.querySelector('.fa-step-backward') const playBTN = document.querySelector('.fa-play') const nextBTN = document.querySelector('.fa-step-forward') const muteBTN = document.querySelector('.fa-volume-mute') const volumeBTN = document.querySelector('.fa-volume-up') const volumeRange = document.querySelector('.volume-range') const sidebarMusic = document.querySelector('.sidebar-music'); const musicBoxContainer = document.querySelector('.music-box-container'); const songTime = document.querySelector('song-time') const songDuration = document.querySelector('.duration-range') const openMusicList = document.querySelector('.nav-player i.fa-bars') const closeMusicList = document.querySelector('.sidebar-music i.fa-times') let duration = 0; let currentTime = 0; let songIndex = 0; let isPlaying = false; let Muted = false const audioEl = new Audio() const allSongs = [ { name: 'Paradise', artist: 'Coldplay', thumb: 'img/artist3.jpg', source: 'songs/audio1.mp3' }, { name: 'Lie to Me', artist: '<NAME> & <NAME>', thumb: 'img/artist4.jpg', source: 'songs/audio2.mp3' }, { name: 'Dead of Night', artist: 'If Found', thumb: 'img/artist5.jpg', source: 'songs/audio3.mp3' }, { name: 'Lose Your Self', artist: 'Eminem', thumb: 'img/artist6.jpg', source: 'songs/audio4.mp3' }, { name: 'Such a Whore', artist: 'JVLA', thumb: 'img/artist7.jpg', source: 'songs/audio5.mp3' }, { name: '<NAME>', artist: '<NAME>', thumb: 'img/artist8.jpg', source: 'songs/audio6.mp3' } ]; let totalSongs = allSongs.length - 1; muteBTN.addEventListener('click', ()=>{ if(Muted){ audioEl.muted = false muteBTN.style.backgroundColor = '#030D13'; Muted = false }else{ audioEl.muted = true muteBTN.style.backgroundColor = '#430000'; Muted = true } }) volumeBTN.addEventListener('click', ()=>{ const volumeMenu = document.querySelector('.volume-menu') volumeBTN.classList.toggle('volumeUpOpen') volumeMenu.classList.toggle('openVolumeMenu') }) volumeRange.addEventListener('input', ()=>{ const volumeSpan = document.querySelector('.volume-menu span') audioEl.volume = (volumeRange.value / 100) volumeSpan.innerHTML = `${volumeRange.value}%` }) openMusicList.addEventListener('click', ()=>{ sidebarMusic.classList.add('OpenSidebar') }) closeMusicList.addEventListener('click', ()=>{ sidebarMusic.classList.remove('OpenSidebar') }) function createSidebarElements(){ for(let i in allSongs){ const musicBox = document.createElement('div') const artistContent = document.createElement('div') const artistiImage = document.createElement('img') const artistText = document.createElement('div') const artistTextH1 = document.createElement('h1') const artistTextP = document.createElement('p') const iconPlay = document.createElement('i') musicBox.classList.add('music-box') artistContent.classList.add('artist-content') artistText.classList.add('artist-text') iconPlay.classList.add('fas','fa-play') musicBoxContainer.appendChild(musicBox) musicBox.appendChild(artistContent) artistContent.appendChild(artistiImage) artistiImage.src = allSongs[i].thumb artistContent.appendChild(artistText) artistText.appendChild(artistTextH1) artistText.appendChild(artistTextP) artistTextH1.innerHTML = allSongs[i].name artistTextP.innerHTML = allSongs[i].artist musicBox.appendChild(iconPlay) iconPlay.addEventListener('click', ()=>{ songIndex = i loadSong() playSong() changeActiveBox() }) } musicBoxContainer.children[0].classList.add('activeBox') } songDuration.addEventListener('input', ()=>{ audioEl.currentTime = songDuration.value; }) audioEl.addEventListener("timeupdate", ()=>{ songDuration.value = audioEl.currentTime duration = audioEl.duration songDuration.max = duration }) audioEl.addEventListener('ended', nextSong) prevBTN.addEventListener('click', ()=>{ if(songIndex === 0){ songIndex = totalSongs; loadSong(); playSong(); }else{ songIndex-- loadSong() playSong() } changeActiveBox() }) playBTN.addEventListener('click', ()=>{ if(isPlaying){ pauseSong() }else{ playSong() } }) nextBTN.addEventListener('click', nextSong) function nextSong(){ if(songIndex === totalSongs){ songIndex = 0; loadSong(); playSong(); }else{ songIndex++ loadSong() playSong() } changeActiveBox() } function pauseSong(){ audioEl.pause() isPlaying = false; audioEl.autoplay = false playBTN.classList.remove('pauseIcon') } function playSong(){ audioEl.play() audioEl.autoplay = true isPlaying = true; playBTN.classList.add('pauseIcon') } function loadSong(){ let currentVolume = (volumeRange.value / 100) audioEl.src = allSongs[songIndex].source audioEl.volume = currentVolume songTittle.innerHTML = allSongs[songIndex].name artistName.innerHTML = allSongs[songIndex].artist artistiIMG.src = allSongs[songIndex].thumb } function changeActiveBox(){ for(let n in allSongs){ musicBoxContainer.children[n].classList.remove('activeBox') musicBoxContainer.children[songIndex].classList.add('activeBox') } } function init(){ loadSong() createSidebarElements() } init()
a4249d7cb7f3de682e8c4ea1569eaa5e8a657e52
[ "JavaScript" ]
1
JavaScript
joseLucas-code/Music-Player-WEB
5dc47e5ae8f6f37afb8efbd067c4850269d105d2
0de3a0b3c9bef9790e93f900f78bd206aaaf4669
refs/heads/master
<file_sep>#include<stdio.h> #include<stdlib.h> /* algoritmo: exemplo simples de uma Equacao do segundo grau. autor: <NAME> email: <EMAIL> ano: 10/04/2019 */ float get_delta(int a, int b, int c){ // Δ = b2 – 4ac //delta = (b*b) - (4*a*c); // delta==196; float delta; delta = (b * b) - ((4 * a) *(c)); return delta; } int get_raizq(int num){ int raiz_quadrada = 0; //premissa ... raiz quadrada de um numero é igual ao resultado da multiplicao de um numero por ele mesmo. for (int i = 1; i < num; i++) { int raiz = i * i; /* code */ if (raiz == num) { /* code */ raiz_quadrada = i; }//if }//for return raiz_quadrada; } void get_bhaskara(float a, float b, float c, float raiz){ //– b ± √Δ/2.a //√196=14 float x1, x2; //x1 = (-b + 14)/2*a; //x2 = (-b - 14)/2*a; x1 = (-(b + raiz))/(2*a); x2 = (-(b - raiz))/(2*a); printf(" X1 linha e: %0.f\n", x1); printf(" X2 linha e: %0.f\n", x2); } int main() { /*------------------ ---------EQUACAO DE SEGUNDO GRAU -------------------------------------*/ /*-----------------------------------------------------------------------------------------*/ //x2 + 12x – 13 = 0 // atribuindo os valores as variaveis para resolver em bhaskara ... – b ± √Δ/2.a int a, b, c; a = 1; b = 12; c = -13; // Descobrindo Delta . . . // Δ = b2 – 4ac float delta = get_delta(a, b, c); //Tirando a raiz quadrada de delta ... float raiz = get_raizq(delta); //Resolvendo a equacao com Bhaskara ... //– b ± √Δ/2.a get_bhaskara(a, b, c, raiz); //x1 = (-b + √Δ)/2*a; //x2 = (-b - √Δ)/2*a; return 0; } <file_sep>algoritmo: Equacao do segundo grau.<br> autor: <NAME><br> email: <EMAIL><br> ano: 10/04/2019<br> decrição:<br><br> Exemplo de uma equação de segundo grau simples utilizando C/C++
e733fafde1756b267294bd48e77d6da02398114f
[ "Markdown", "C++" ]
2
C++
Andre17Nas/equacao_segundo_grau
216609ba02b3213f1d035767e49cec3131eb1bd5
d03697a713d40eb6415081d1a553c675939c75b1
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using Unity.Entities; namespace VRBattleRoyale { [System.Serializable] public class CharacterController : IComponentData { } } <file_sep>namespace VRBattleRoyale { public enum MovementOrientationModeEnum { Hand, Head } }<file_sep>namespace VRBattleRoyale { public enum InputLayoutEnum { Default, Southpaw } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace VRBattleRoyale { [CreateAssetMenu(fileName = "New Player Motor Variables", menuName = "ScriptableObjects/Player Motor Variables")] public class PlayerMotorVariables : ScriptableObject { public float MovementSpeed = 7f; public float JumpSpeed = 7f; public float JumpDuration = 0.2f; public float ExtraJumpTimeAfterLeavingGround = 0.15f; public float StepHeightWorldUnits = 0.4f; public int SlopeLimit = 70; [Range(0f, 1f)] public float AirControl = 0.4f; public float Gravity = 30f; public float SlideGravity = 30f; public float AirFriction = 0.5f; public float GroundFriction = 100f; public float SmoothRotationMultiplier = 30; public float SnapRotationCooldown = 0.3f; public float CrouchDistance = 0.5f; public float CameraForwardOffset = -0.05f; public float CameraSmoothTime = 0.05f; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace VRBattleRoyale { public static class Vector2Util { public static Vitruvius.Generated.Vector2 ConvertToSpatialOSVector2(UnityEngine.Vector2 Vector2) { return new Vitruvius.Generated.Vector2(Vector2.x, Vector2.y); } public static UnityEngine.Vector2 ConvertToUnityVector2(Vitruvius.Generated.Vector2 Vector2) { return new UnityEngine.Vector2(Vector2.X, Vector2.Y); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace VRBattleRoyale { public static class Vector3Util { public static Vitruvius.Generated.Vector3 ConvertToSpatialOSVector3(UnityEngine.Vector3 vector3) { return new Vitruvius.Generated.Vector3(vector3.x, vector3.y, vector3.z); } public static UnityEngine.Vector3 ConvertToUnityVector3(Vitruvius.Generated.Vector3 vector3) { return new UnityEngine.Vector3(vector3.X, vector3.Y, vector3.Z); } } } <file_sep>using System; using System.Collections; using UnityEngine; using Improbable.Gdk.Core; using Improbable.Gdk.Mobile; using Improbable.Gdk.PlayerLifecycle; using Improbable.Gdk.GameObjectCreation; namespace VRBattleRoyale { public class MobileClientWorkerConnector : UnityClientConnector, MobileConnectionFlowInitializer.IMobileSettingsProvider { #pragma warning disable 649 [SerializeField] private string ipAddress; #pragma warning restore 649 public new const string WorkerType = "MobileClient"; #region Unity Life Cycle private async void Start() { var connParams = CreateConnectionParameters(WorkerType, new MobileConnectionParametersInitializer()); var flowInitializer = new MobileConnectionFlowInitializer( new MobileConnectionFlowInitializer.CommandLineSettingsProvider(), new MobileConnectionFlowInitializer.PlayerPrefsSettingsProvider(), this); var builder = new SpatialOSConnectionHandlerBuilder() .SetConnectionParameters(connParams); switch (flowInitializer.GetConnectionService()) { case ConnectionService.Receptionist: builder.SetConnectionFlow(new ReceptionistFlow(CreateNewWorkerId(WorkerType), flowInitializer)); break; case ConnectionService.Locator: builder.SetConnectionFlow(new LocatorFlow(flowInitializer)); break; default: throw new ArgumentException("Received unsupported connection service."); } await Connect(builder, new ForwardingDispatcher()).ConfigureAwait(false); } #endregion #region Overrides protected override string GetAuthPlayerPrefabPath() { return "Prefabs/MobileClient/Authoritative/Player"; } protected override string GetNonAuthPlayerPrefabPath() { return "Prefabs/MobileClient/NonAuthoritative/Player"; } #endregion public Option<string> GetReceptionistHostIp() { return string.IsNullOrEmpty(ipAddress) ? Option<string>.Empty : new Option<string>(ipAddress); } public Option<string> GetDevAuthToken() { var token = Resources.Load<TextAsset>("DevAuthToken")?.text.Trim(); return token ?? Option<string>.Empty; } public Option<ConnectionService> GetConnectionService() { return Option<ConnectionService>.Empty; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace VRBattleRoyale { public static class Utilities { public static bool IsDevelopment { get { return Application.isEditor || Debug.isDebugBuild; } } } } <file_sep>namespace VRBattleRoyale { public enum FaderStateEnum { FadingOn, On, FadingOff, Off } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace VRBattleRoyale { public class PlayerSettingsManager : MonoBehaviour { private static PlayerSettingsManager instance; public static PlayerSettingsManager Instance { get { return instance; } } [SerializeField] private PlayerSettings playerSettings; public delegate void SettingsChangedEvent(); public SettingsChangedEvent OnDominantHandChanged; public SettingsChangedEvent OnInputLayoutChanged; public SettingsChangedEvent OnRotationModeChanged; public SettingsChangedEvent OnSnapRotationDegreesChanged; public SettingsChangedEvent OnSmoothRotationSpeedChanged; public SettingsChangedEvent OnMovementOrientationModeChanged; public SettingsChangedEvent OnRoomSetupChanged; public SettingsChangedEvent OnFOVBlindersEnabledChanged; public SettingsChangedEvent OnFOVBlindersStrengthChanged; public HandednessEnum DominantHand { get { return playerSettings.DominantHand; } set { playerSettings.DominantHand = value; if(OnDominantHandChanged != null) { OnDominantHandChanged(); } } } public InputLayoutEnum InputLayout { get { return playerSettings.InputLayout; } set { playerSettings.InputLayout = value; if (OnInputLayoutChanged != null) { OnInputLayoutChanged(); } } } public RotationModeEnum RotationMode { get { return playerSettings.RotationMode; } set { playerSettings.RotationMode = value; if (OnRotationModeChanged != null) { OnRotationModeChanged(); } } } public int SnapRotationDegrees { get { return playerSettings.SnapRotationDegrees; } set { var found = false; for(var i = 0; i < PlayerSettings.SNAP_DEGREES.Length; i++) { if(value == PlayerSettings.SNAP_DEGREES[i]) { found = true; break; } } if(!found) { return; } playerSettings.SnapRotationDegrees = value; if (OnSnapRotationDegreesChanged != null) { OnSnapRotationDegreesChanged(); } } } public float SmoothRotationSpeed { get { return playerSettings.SmoothRotationSpeed; } set { playerSettings.SmoothRotationSpeed = Mathf.Clamp(value, PlayerSettings.MIN_SMOOTH_ROTATION, PlayerSettings.MAX_SMOOTH_ROTATION); if (OnSmoothRotationSpeedChanged != null) { OnSmoothRotationSpeedChanged(); } } } public MovementOrientationModeEnum MovementOrientationMode { get { return playerSettings.MovementOrientationMode; } set { playerSettings.MovementOrientationMode = value; if(OnMovementOrientationModeChanged != null) { OnMovementOrientationModeChanged(); } } } public RoomSetupEnum RoomSetup { get { return playerSettings.RoomSetup; } set { playerSettings.RoomSetup = value; if(OnRoomSetupChanged != null) { OnRoomSetupChanged(); } } } public bool FOVBlindersEnabled { get { return playerSettings.fovBlindersEnabled; } set { playerSettings.fovBlindersEnabled = value; if(OnFOVBlindersEnabledChanged != null) { OnFOVBlindersEnabledChanged(); } } } public int FOVBlindersStrength { get { return playerSettings.fovBlindersStrength; } set { playerSettings.fovBlindersStrength = Mathf.Clamp(value, PlayerSettings.MIN_FOV_BLINDERS_STRENGTH, PlayerSettings.MAX_FOV_BLINDERS_STRENGTH); if (OnFOVBlindersStrengthChanged != null) { OnFOVBlindersStrengthChanged(); } } } #region Unity Life Cycle private void Awake() { if (instance != null) { #if UNITY_EDITOR DestroyImmediate(gameObject); #else Destroy(gameObject); #endif return; } instance = this; DontDestroyOnLoad(gameObject); } private void OnDestroy() { if (instance == this) { instance = null; OnDominantHandChanged = null; OnInputLayoutChanged = null; OnRotationModeChanged = null; OnSnapRotationDegreesChanged = null; OnSmoothRotationSpeedChanged = null; OnMovementOrientationModeChanged = null; OnRoomSetupChanged = null; OnFOVBlindersEnabledChanged = null; OnFOVBlindersStrengthChanged = null; } } #endregion } } <file_sep>namespace VRBattleRoyale { public enum RotationModeEnum { Snap, Smooth } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using UnityEditor.SceneManagement; //This editor script displays the inspector GUI of the mover components; //It also updates the collider dimensions whenever a value is changed in the inspector; [CustomEditor(typeof(Mover))] public class MoverInspector : Editor { private Mover mover; private string[] physicsLayers; private Vector3[] raycastArrayPositions; void Start() { Setup(); } void Reset() { Setup(); } void OnEnable() { Setup(); } void Setup() { mover = (Mover)target; List<string> _layers = new List<string>(); for(int i = 0; i < 32; i ++) { _layers.Add(LayerMask.LayerToName(i)); } physicsLayers = _layers.ToArray(); raycastArrayPositions = Sensor.GetRaycastStartPositions(mover.sensorArrayRows, mover.sensorArrayRayCount, mover.sensorArrayRowsAreOffset, 1f); } public override void OnInspectorGUI() { if(mover == null) { Setup(); return; } GUILayout.Label("Mover Options", EditorStyles.boldLabel); Rect _space; EditorGUI.BeginChangeCheck(); mover.stepHeight = EditorGUILayout.Slider("Step Height", mover.stepHeight, 0f, 1f); GUILayout.Label("Collider Options", EditorStyles.boldLabel); mover.colliderHeight = EditorGUILayout.FloatField("Collider Height", mover.colliderHeight); mover.colliderThickness = EditorGUILayout.FloatField("Collider Thickness",mover.colliderThickness); mover.colliderOffset = EditorGUILayout.Vector3Field("Collider Offset", mover.colliderOffset); if(EditorGUI.EndChangeCheck()) { mover.RecalculateColliderDimensions(); OnEditorVariableChanged(); } GUILayout.Label("Sensor Options", EditorStyles.boldLabel); EditorGUI.BeginChangeCheck(); mover.sensorType = (Sensor.CastType)EditorGUILayout.EnumPopup("Sensor Type", mover.sensorType); mover.sensorLayermask = EditorGUILayout.MaskField("Layermask", mover.sensorLayermask, physicsLayers); mover.isInDebugMode = EditorGUILayout.Toggle("Debug Mode",mover.isInDebugMode); if(EditorGUI.EndChangeCheck()) { OnEditorVariableChanged(); } if(mover.sensorType == Sensor.CastType.RaycastArray) GUILayout.Label("Advanced Options", EditorStyles.centeredGreyMiniLabel); GUILayout.Space(5); if(mover.sensorType == Sensor.CastType.Raycast) { } else if(mover.sensorType == Sensor.CastType.Spherecast) { } else if(mover.sensorType == Sensor.CastType.RaycastArray) { if(raycastArrayPositions == null) raycastArrayPositions = Sensor.GetRaycastStartPositions(mover.sensorArrayRows, mover.sensorArrayRayCount, mover.sensorArrayRowsAreOffset, 1f); EditorGUI.BeginChangeCheck(); mover.sensorArrayRayCount = EditorGUILayout.IntSlider("Number", mover.sensorArrayRayCount, 3, 9); mover.sensorArrayRows = EditorGUILayout.IntSlider("Rows", mover.sensorArrayRows, 1, 5); mover.sensorArrayRowsAreOffset = EditorGUILayout.Toggle("Offset Rows", mover.sensorArrayRowsAreOffset); if(EditorGUI.EndChangeCheck()) { raycastArrayPositions = Sensor.GetRaycastStartPositions(mover.sensorArrayRows, mover.sensorArrayRayCount, mover.sensorArrayRowsAreOffset, 1f); OnEditorVariableChanged(); } GUILayout.Space(5); _space = GUILayoutUtility.GetRect(GUIContent.none, GUIStyle.none, GUILayout.Height(100)); Rect background = new Rect(_space.x + (_space.width - _space.height)/2f, _space.y, _space.height, _space.height); EditorGUI.DrawRect(background, Color.grey); float point_size = 3f; Vector2 center = new Vector2(background.x + background.width/2f, background.y + background.height/2f); if(raycastArrayPositions != null && raycastArrayPositions.Length != 0) { for(int i = 0; i < raycastArrayPositions.Length; i++) { Vector2 position = center + new Vector2(raycastArrayPositions[i].x, raycastArrayPositions[i].z) * background.width/2f * 0.9f; EditorGUI.DrawRect(new Rect(position.x - point_size/2f, position.y - point_size/2f, point_size, point_size), Color.white); } } if(raycastArrayPositions != null && raycastArrayPositions.Length != 0) GUILayout.Label("Number of rays = " + raycastArrayPositions.Length, EditorStyles.centeredGreyMiniLabel ); } } void OnEditorVariableChanged() { if(!Application.isPlaying) { EditorUtility.SetDirty(mover); EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace VRBattleRoyale { public class FOVBlinders : MonoBehaviour { [SerializeField] private float fadeInTime = 0.2f; [SerializeField] private float fadeOutTime = 0.1f; [SerializeField] private Vector2 outterBounds = Vector2.zero; [SerializeField] private Vector2 innerBoundsMax = Vector2.zero; [SerializeField] private Vector2 innerBoundsMin = Vector2.zero; [SerializeField] private RectTransform blinderRectTransform; [SerializeField] private RectTransform[] boarderRectTransforms = new RectTransform[0]; private FaderStateEnum currentState = FaderStateEnum.Off; private float percentOn = 0f; private Vector2 stepBounds = Vector2.zero; private Coroutine fadeCoroutine; #region Unity Lifecycle private void Awake() { stepBounds = (innerBoundsMax - innerBoundsMin) / PlayerSettings.MAX_FOV_BLINDERS_STRENGTH; } private void OnEnable() { fadeCoroutine = null; PlayerSettingsManager.Instance.OnFOVBlindersEnabledChanged += FOVBlindersEnableChanged; } #if UNITY_EDITOR private void OnValidate() { ChangeSize(innerBoundsMax); } #endif private void OnDisable() { if (PlayerSettingsManager.Instance) { PlayerSettingsManager.Instance.OnFOVBlindersEnabledChanged -= FOVBlindersEnableChanged; } } #endregion #region Event Listeners private void FOVBlindersEnableChanged() { if (!PlayerSettingsManager.Instance.FOVBlindersEnabled) { if (fadeCoroutine != null) StopCoroutine(fadeCoroutine); fadeCoroutine = null; ChangeSize(innerBoundsMax); percentOn = 0f; currentState = FaderStateEnum.Off; } } #endregion public void FadeBlindersIn() { if (!PlayerSettingsManager.Instance.FOVBlindersEnabled || currentState == FaderStateEnum.FadingOn || currentState == FaderStateEnum.On) return; if (fadeCoroutine != null) StopCoroutine(fadeCoroutine); fadeCoroutine = StartCoroutine(FadeOnCoroutine()); } private IEnumerator FadeOnCoroutine() { currentState = FaderStateEnum.FadingOn; var timer = fadeInTime * percentOn; var targetSize = innerBoundsMax - (stepBounds * PlayerSettingsManager.Instance.FOVBlindersStrength); while (timer < fadeInTime) { timer += Time.deltaTime; percentOn = timer / fadeInTime; ChangeSize(Vector2.Lerp(innerBoundsMax, targetSize, percentOn)); yield return null; } ChangeSize(targetSize); percentOn = 1f; currentState = FaderStateEnum.On; fadeCoroutine = null; } public void FadeBlindersOut() { if (currentState == FaderStateEnum.FadingOff || currentState == FaderStateEnum.Off) return; if (fadeCoroutine != null) StopCoroutine(fadeCoroutine); fadeCoroutine = StartCoroutine(FadeOffCoroutine()); } private IEnumerator FadeOffCoroutine() { currentState = FaderStateEnum.FadingOff; var timer = (1f - percentOn) * fadeOutTime; var targetSize = innerBoundsMax - (stepBounds * PlayerSettingsManager.Instance.FOVBlindersStrength); while (timer < fadeOutTime) { timer += Time.deltaTime; percentOn = 1f - (timer / fadeOutTime); ChangeSize(Vector2.Lerp(innerBoundsMax, targetSize, percentOn)); yield return null; } ChangeSize(innerBoundsMax); percentOn = 0f; currentState = FaderStateEnum.Off; fadeCoroutine = null; } private void ChangeSize(Vector2 size) { blinderRectTransform.sizeDelta = size; var sideSize = new Vector2((outterBounds.x - size.x) * 0.5f, size.y); var sideAnchorPosition = new Vector2(((size.x * 0.5f) + (sideSize.x * 0.5f)), 0f); boarderRectTransforms[0].sizeDelta = sideSize; boarderRectTransforms[0].anchoredPosition = -sideAnchorPosition; boarderRectTransforms[1].sizeDelta = sideSize; boarderRectTransforms[1].anchoredPosition = sideAnchorPosition; var topBottomSize = new Vector2(outterBounds.x, (outterBounds.y - size.y) * 0.5f); var topBottomAnchorPosition = new Vector2(0f, ((size.y * 0.5f) + (topBottomSize.y * 0.5f))); boarderRectTransforms[2].sizeDelta = topBottomSize; boarderRectTransforms[2].anchoredPosition = topBottomAnchorPosition; boarderRectTransforms[3].sizeDelta = topBottomSize; boarderRectTransforms[3].anchoredPosition = -topBottomAnchorPosition; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace VRBattleRoyale { [CreateAssetMenu(fileName = "New Session Settings", menuName = "ScriptableObjects/Session Settings")] public class SessionSettings : ScriptableObject { public HMDTypeEnum HMDType = HMDTypeEnum.OculusQuest; public PlatformEnum Platform = PlatformEnum.OculusHome; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace VRBattleRoyale { [CreateAssetMenu(fileName = "New Player Settings", menuName = "ScriptableObjects/Player Settings")] public class PlayerSettings : ScriptableObject { public static float MIN_SMOOTH_ROTATION = 0.5f; public static float MAX_SMOOTH_ROTATION = 10f; public static int[] SNAP_DEGREES = { 15, 30, 45, 60, 90 }; public static int MIN_FOV_BLINDERS_STRENGTH = 1; public static int MAX_FOV_BLINDERS_STRENGTH = 10; public HandednessEnum DominantHand = HandednessEnum.Right; public InputLayoutEnum InputLayout = InputLayoutEnum.Default; public RotationModeEnum RotationMode = RotationModeEnum.Snap; public int SnapRotationDegrees = 30; public float SmoothRotationSpeed = 5; public MovementOrientationModeEnum MovementOrientationMode = MovementOrientationModeEnum.Hand; public RoomSetupEnum RoomSetup = RoomSetupEnum.Roomscale; public bool fovBlindersEnabled = true; public int fovBlindersStrength = 5; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using Unity.Entities; using Unity.Mathematics; namespace VRBattleRoyale { public class PlayerManager : MonoBehaviour, IReceiveEntity { private static PlayerManager instance; public static PlayerManager Instance { get { return instance; } } [SerializeField] private Transform rigTransform; [SerializeField] private FOVBlinders fovBlinders; [SerializeField] private float smoothRotationMultiplier = 30; [SerializeField] private float snapRotationCooldown = 0.3f; private float lastSnapRotationTime = 0f; private Entity characterControllerEntity = Entity.Null; public Transform RigTransform { get { return rigTransform; } } public FOVBlinders FOVBlinders { get { return fovBlinders; } } #region Unity Life Cycle private void Awake() { if(instance != null) { Destroy(gameObject); return; } instance = this; } private void Update() { if (!string.IsNullOrEmpty(UnityEngine.XR.XRSettings.loadedDeviceName)) { UnityEngine.XR.XRDevice.SetTrackingSpaceType(UnityEngine.XR.TrackingSpaceType.RoomScale); Camera.main.fieldOfView = math.degrees((float)UnityEngine.XR.XRSettings.eyeTextureWidth / UnityEngine.XR.XRSettings.eyeTextureHeight) * 2.0f; } HandleRotationInput(); } private void OnDestroy() { if(instance == this) { instance = null; } } #endregion #region Event Listeners public void SetReceivedEntity(Entity entity) { characterControllerEntity = entity; } #endregion private void HandleRotationInput() { var rotationInput = InputManager.Instance.RotationInput; if (rotationInput == 0f) { return; } var deltaRotation = 0f; if (PlayerSettingsManager.Instance.RotationMode == RotationModeEnum.Smooth) { deltaRotation = rotationInput * PlayerSettingsManager.Instance.SmoothRotationSpeed * smoothRotationMultiplier * Time.fixedDeltaTime; } else { if (Time.time - lastSnapRotationTime >= snapRotationCooldown) { lastSnapRotationTime = Time.time; deltaRotation = rotationInput > 0 ? PlayerSettingsManager.Instance.SnapRotationDegrees : -PlayerSettingsManager.Instance.SnapRotationDegrees; } } if (deltaRotation != 0f) { var yEulerAngle = 0f; if (PlayerSettingsManager.Instance.RoomSetup == RoomSetupEnum.Roomscale) { yEulerAngle = Camera.main.transform.eulerAngles.y + deltaRotation; } else { yEulerAngle = RigTransform.eulerAngles.y + deltaRotation; } TeleportPlayerHead(Camera.main.transform.position, yEulerAngle); } } #region Teleports private void TeleportPlayerRoom(Vector3 desiredWorldPositionOfRoom, Quaternion desiredWordRotationOfRoom) { transform.rotation = desiredWordRotationOfRoom; transform.position = desiredWorldPositionOfRoom; } private void TeleportPlayerHead(Vector3 desiredWorldPositionOfCamera) { TeleportPlayerRoom(desiredWorldPositionOfCamera + (transform.position - Camera.main.transform.position), transform.rotation); } private void TeleportPlayerHead(Vector3 desiredWorldPositionOfCamera, float lookAtYEulerAngle) { if (PlayerSettingsManager.Instance.RoomSetup == RoomSetupEnum.Roomscale) { TeleportPlayerRoom(desiredWorldPositionOfCamera + (Quaternion.Euler(0f, lookAtYEulerAngle - Camera.main.transform.eulerAngles.y, 0f) * (transform.position - Camera.main.transform.position)), Quaternion.Euler(0f, lookAtYEulerAngle - Camera.main.transform.localEulerAngles.y, 0f)); } else { TeleportPlayerRoom(desiredWorldPositionOfCamera + (Quaternion.Euler(0f, lookAtYEulerAngle - transform.eulerAngles.y, 0f) * (transform.position - Camera.main.transform.position)), Quaternion.Euler(0f, lookAtYEulerAngle, 0f)); } } #endregion } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace VRBattleRoyale { public class SessionSettingsManager : MonoBehaviour { private static SessionSettingsManager instance; public static SessionSettingsManager Instance { get { return instance; } } [SerializeField] private SessionSettings sessionSettings; public HMDTypeEnum CurrentHMDType { get { return sessionSettings.HMDType; } } #region Unity Life Cycle private void Awake() { if (instance != null) { #if UNITY_EDITOR DestroyImmediate(gameObject); #else Destroy(gameObject); #endif return; } instance = this; DontDestroyOnLoad(gameObject); #if !UNITY_EDITOR Debug.Log("TODO - REFINE THIS TO CHECK DEVICE NAME AND IF ITS LOADED?"); if (Application.platform == RuntimePlatform.WindowsPlayer) { if (UnityEngine.XR.XRSettings.loadedDeviceName.ToLower().Equals("oculus")) sessionSettings.HMDType = HMDTypeEnum.OculusRift; else if (UnityEngine.XR.XRSettings.loadedDeviceName.ToLower().Equals("openvr")) sessionSettings.HMDType = HMDTypeEnum.OpenVR; } else if (Application.platform == RuntimePlatform.Android) { sessionSettings.HMDType = HMDTypeEnum.OculusQuest; } else if (Application.platform == RuntimePlatform.PS4) { sessionSettings.HMDType = HMDTypeEnum.PlayStationVR; } #endif if(sessionSettings.HMDType == HMDTypeEnum.OculusQuest) { Time.fixedDeltaTime = 1 / 72f; } else if (sessionSettings.HMDType == HMDTypeEnum.OculusRift) { Time.fixedDeltaTime = 1 / 90f; } else if (sessionSettings.HMDType == HMDTypeEnum.OpenVR) { Time.fixedDeltaTime = 1 / 90f; } else if (sessionSettings.HMDType == HMDTypeEnum.PlayStationVR) { Time.fixedDeltaTime = 1 / 60f; } } private void OnDestroy() { if (instance == this) { instance = null; } } #endregion } } <file_sep>using System; using System.Collections; using UnityEngine; using Improbable.Gdk.Core; using Improbable.Gdk.PlayerLifecycle; using Improbable.Gdk.GameObjectCreation; using Improbable.Worker.CInterop; namespace VRBattleRoyale { public class UnityGameLogicConnector : WorkerConnector { public const string WorkerType = "UnityGameLogic"; [SerializeField] private GameObject level; private GameObject levelInstance; #region Unity Life Cycle private async void Start() { PlayerLifecycleConfig.CreatePlayerEntityTemplate = EntityTemplates.CreatePlayerEntityTemplate; IConnectionFlow flow; ConnectionParameters connectionParameters; if (Application.isEditor) { flow = new ReceptionistFlow(CreateNewWorkerId(WorkerType)); connectionParameters = CreateConnectionParameters(WorkerType); } else { flow = new ReceptionistFlow(CreateNewWorkerId(WorkerType), new CommandLineConnectionFlowInitializer()); connectionParameters = CreateConnectionParameters(WorkerType, new CommandLineConnectionParameterInitializer()); } var builder = new SpatialOSConnectionHandlerBuilder() .SetConnectionFlow(flow) .SetConnectionParameters(connectionParameters); await Connect(builder, new ForwardingDispatcher()).ConfigureAwait(false); } #endregion #region Overrides protected override void HandleWorkerConnectionEstablished() { Worker.World.GetOrCreateSystem<MetricSendSystem>(); PlayerLifecycleHelper.AddServerSystems(Worker.World); GameObjectCreationHelper.EnableStandardGameObjectCreation(Worker.World); if (level != null) { levelInstance = Instantiate(level, transform.position, transform.rotation); } } public override void Dispose() { if (levelInstance != null) { Destroy(levelInstance); } base.Dispose(); } #endregion } } <file_sep>namespace VRBattleRoyale { public enum HMDTypeEnum { OculusQuest, OculusRift, OpenVR, PlayStationVR } } <file_sep>namespace VRBattleRoyale { public enum PlayerMotorStateEnum { Grounded, Sliding, Falling, Rising, Jumping } } <file_sep>namespace VRBattleRoyale { public enum PlatformEnum { OculusHome, Steam, PlayStation } } <file_sep>using System; using System.Collections; using UnityEngine; using Improbable.Gdk.Core; using Improbable.Gdk.PlayerLifecycle; using Improbable.Gdk.GameObjectCreation; using Improbable.Worker.CInterop; namespace VRBattleRoyale { public class UnityClientConnector : WorkerConnector { public const string WorkerType = "UnityClient"; [SerializeField] private GameObject level; private GameObject levelInstance; private AdvancedEntityPipeline entityPipeline; public event Action OnLostPlayerEntity; #region Unity Life Cycle private async void Start() { var connParams = CreateConnectionParameters(WorkerType); connParams.Network.ConnectionType = NetworkConnectionType.Kcp; var builder = new SpatialOSConnectionHandlerBuilder().SetConnectionParameters(connParams); if (!Application.isEditor) { var initializer = new CommandLineConnectionFlowInitializer(); switch (initializer.GetConnectionService()) { case ConnectionService.Receptionist: builder.SetConnectionFlow(new ReceptionistFlow(CreateNewWorkerId(WorkerType), initializer)); break; case ConnectionService.Locator: builder.SetConnectionFlow(new LocatorFlow(initializer)); break; default: throw new ArgumentOutOfRangeException(); } } else { builder.SetConnectionFlow(new ReceptionistFlow(CreateNewWorkerId(WorkerType))); } await Connect(builder, new ForwardingDispatcher()).ConfigureAwait(false); } #endregion #region Overrides protected override void HandleWorkerConnectionEstablished() { PlayerLifecycleHelper.AddClientSystems(Worker.World); PlayerLifecycleConfig.MaxPlayerCreationRetries = 0; entityPipeline = new AdvancedEntityPipeline(Worker, GetAuthPlayerPrefabPath(), GetNonAuthPlayerPrefabPath()); entityPipeline.OnRemovedAuthoritativePlayer += RemovingAuthoritativePlayer; GameObjectCreationHelper.EnableStandardGameObjectCreation(Worker.World, entityPipeline, gameObject); if (level != null) { levelInstance = Instantiate(level, transform.position, transform.rotation); } } public override void Dispose() { if (levelInstance != null) { Destroy(levelInstance); } base.Dispose(); } #endregion protected virtual string GetAuthPlayerPrefabPath() { return "Prefabs/UnityClient/Authoritative/Player"; } protected virtual string GetNonAuthPlayerPrefabPath() { return "Prefabs/UnityClient/NonAuthoritative/Player"; } private void RemovingAuthoritativePlayer() { Debug.LogError($"Player entity got removed while still being connected. Disconnecting..."); OnLostPlayerEntity?.Invoke(); } } } <file_sep>namespace VRBattleRoyale { public enum RoomSetupEnum { Roomscale, FrontFacing } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace VRBattleRoyale { public class PlayerMotor_Singleplayer : MonoBehaviour { [SerializeField] private PlayerMotorVariables motorVariables; [SerializeField] private Mover mover; [SerializeField] private Rigidbody moverRigidbody; [SerializeField] private SphereCollider headCollider; private PlayerMotorStateEnum currentMotorState = PlayerMotorStateEnum.Falling; private Vector3 momentum = Vector3.zero; private Vector3 savedVelocity = Vector3.zero; private Vector3 savedMovementVelocity = Vector3.zero; private Vector3 savedPlayerLocalPosition = Vector3.zero; private Vector3 smoothVelocity = Vector3.zero; private float jumpStartTime = 0f; private float snapRotationTime = 0f; private float lastGroundedTime = 0f; private bool crouching = false; private bool jumpPressed = false; public bool IsGrounded { get { return (currentMotorState == PlayerMotorStateEnum.Grounded || currentMotorState == PlayerMotorStateEnum.Sliding); } } private float PlayerHeight { get { return Camera.main.transform.localPosition.y - (crouching == true ? motorVariables.CrouchDistance : 0f); } } private Vector3 DesiredHeadPosition { get { var cameraForwardXZ = Camera.main.transform.forward; cameraForwardXZ.y = 0f; return mover.transform.position + (Vector3.up * (mover.colliderHeight - headCollider.radius)) + (cameraForwardXZ.normalized * motorVariables.CameraForwardOffset); } } public delegate void PlayerMotorVector3Event(Vector3 v); public event PlayerMotorVector3Event OnJump; public event PlayerMotorVector3Event OnLand; #region Unity Life Cycle private void Start() { savedPlayerLocalPosition = Camera.main.transform.localPosition; } private void Update() { TeleportPlayerHead(Vector3.SmoothDamp(Camera.main.transform.position, DesiredHeadPosition, ref smoothVelocity, motorVariables.CameraSmoothTime)); GetInput(); } private void FixedUpdate() { var deltaPlayerLocalPosition = Camera.main.transform.localPosition - savedPlayerLocalPosition; deltaPlayerLocalPosition.y = 0f; moverRigidbody.MovePosition(moverRigidbody.transform.position + (Quaternion.Euler(0f, PlayerManager.Instance.transform.eulerAngles.y, 0f) * new Vector3(deltaPlayerLocalPosition.x, 0f, deltaPlayerLocalPosition.z))); headCollider.transform.position = DesiredHeadPosition; ResizeMover(); mover.CheckForGround(); HandleState(); HandleMomentum(); HandleJumping(); var velocity = CalculateMovementVelocity(); velocity += momentum; mover.SetExtendSensorRange(IsGrounded); mover.SetVelocity(velocity); if (velocity.x != 0f || velocity.y != 0f || velocity.z != 0) { PlayerManager.Instance.FOVBlinders.FadeBlindersIn(); } else { PlayerManager.Instance.FOVBlinders.FadeBlindersOut(); } savedVelocity = velocity; savedMovementVelocity = velocity - momentum; ResetInput(); savedPlayerLocalPosition = Camera.main.transform.localPosition; } private void OnDestroy() { OnJump = null; OnLand = null; } #endregion private void GetInput() { if (!jumpPressed) { jumpPressed = InputManager.Instance.JumpInput; } if (InputManager.Instance.CrouchInput) { if (crouching) { UnCrouch(); } else { Crouch(); } } } private void ResetInput() { jumpPressed = false; } private void ResizeMover() { var newMoverColliderHeight = PlayerHeight + headCollider.radius; var raycastHit = new RaycastHit(); if (Physics.Linecast(mover.transform.position, mover.transform.position + (Vector3.up * newMoverColliderHeight), out raycastHit, mover.sensorLayermask)) { newMoverColliderHeight = raycastHit.distance - 0.01f; } mover.colliderHeight = Mathf.Max(newMoverColliderHeight, headCollider.radius * 2f); if (mover.colliderHeight >= motorVariables.StepHeightWorldUnits + mover.colliderThickness) { mover.stepHeight = motorVariables.StepHeightWorldUnits / mover.colliderHeight; } else { mover.stepHeight = Mathf.Max((mover.colliderHeight - motorVariables.StepHeightWorldUnits) / mover.colliderHeight, 0f); } mover.RecalculateColliderDimensions(); } private void HandleState() { var isRising = IsRisingOrFalling() && (VectorMath.GetDotProduct(momentum, mover.transform.up) > 0f); var isSliding = mover.IsGrounded() && (Vector3.Angle(mover.GetGroundNormal(), mover.transform.up) > motorVariables.SlopeLimit); switch (currentMotorState) { case PlayerMotorStateEnum.Grounded: if (isRising) { currentMotorState = PlayerMotorStateEnum.Rising; GroundContactLost(); break; } if (!mover.IsGrounded()) { currentMotorState = PlayerMotorStateEnum.Falling; GroundContactLost(); break; } if (isSliding) { currentMotorState = PlayerMotorStateEnum.Sliding; break; } lastGroundedTime = Time.time; break; case PlayerMotorStateEnum.Falling: if (isRising) { currentMotorState = PlayerMotorStateEnum.Rising; break; } if (mover.IsGrounded() && !isSliding) { currentMotorState = PlayerMotorStateEnum.Grounded; GroundContactRegained(momentum); break; } if (isSliding) { currentMotorState = PlayerMotorStateEnum.Sliding; GroundContactRegained(momentum); break; } break; case PlayerMotorStateEnum.Sliding: if (isRising) { currentMotorState = PlayerMotorStateEnum.Rising; GroundContactLost(); break; } if (!mover.IsGrounded()) { currentMotorState = PlayerMotorStateEnum.Falling; break; } if (mover.IsGrounded() && !isSliding) { GroundContactRegained(momentum); currentMotorState = PlayerMotorStateEnum.Grounded; break; } break; case PlayerMotorStateEnum.Rising: if (isRising) break; if (mover.IsGrounded() && !isSliding) { currentMotorState = PlayerMotorStateEnum.Grounded; GroundContactRegained(momentum); break; } if (isSliding) { currentMotorState = PlayerMotorStateEnum.Sliding; break; } if (!mover.IsGrounded()) { currentMotorState = PlayerMotorStateEnum.Falling; break; } break; case PlayerMotorStateEnum.Jumping: if ((Time.time - jumpStartTime) > motorVariables.JumpDuration) { currentMotorState = PlayerMotorStateEnum.Rising; break; } break; } } private void HandleMomentum() { var verticalMomentum = Vector3.zero; var horizontalMomentum = Vector3.zero; if (momentum != Vector3.zero) { verticalMomentum = VectorMath.ExtractDotVector(momentum, mover.transform.up); horizontalMomentum = momentum - verticalMomentum; } if (currentMotorState == PlayerMotorStateEnum.Sliding) verticalMomentum -= mover.transform.up * motorVariables.SlideGravity * Time.fixedDeltaTime; else verticalMomentum -= mover.transform.up * motorVariables.Gravity * Time.fixedDeltaTime; if (currentMotorState == PlayerMotorStateEnum.Grounded) verticalMomentum = Vector3.zero; if (IsGrounded) horizontalMomentum = VectorMath.IncrementVectorLengthTowardTargetLength(horizontalMomentum, motorVariables.GroundFriction, Time.fixedDeltaTime, 0f); else horizontalMomentum = VectorMath.IncrementVectorLengthTowardTargetLength(horizontalMomentum, motorVariables.AirFriction, Time.fixedDeltaTime, 0f); momentum = horizontalMomentum + verticalMomentum; if (currentMotorState == PlayerMotorStateEnum.Sliding) { momentum = Vector3.ProjectOnPlane(momentum, mover.GetGroundNormal()); } if (currentMotorState == PlayerMotorStateEnum.Jumping) { momentum = VectorMath.RemoveDotVector(momentum, mover.transform.up); momentum += mover.transform.up * motorVariables.JumpSpeed; } } private void HandleJumping() { if (currentMotorState == PlayerMotorStateEnum.Grounded || ((currentMotorState == PlayerMotorStateEnum.Falling || currentMotorState == PlayerMotorStateEnum.Sliding) && Time.time - lastGroundedTime < motorVariables.ExtraJumpTimeAfterLeavingGround)) { if (jumpPressed) { GroundContactLost(); JumpStart(); currentMotorState = PlayerMotorStateEnum.Jumping; } } } protected Vector3 CalculateMovementVelocity() { var velocity = InputManager.Instance.MoveInput; velocity *= motorVariables.MovementSpeed * Time.fixedDeltaTime; if (!IsGrounded) velocity *= motorVariables.AirControl; if (currentMotorState == PlayerMotorStateEnum.Sliding) { var _factor = Mathf.InverseLerp(90f, 0f, Vector3.Angle(mover.transform.up, mover.GetGroundNormal())); velocity *= _factor; } return velocity; } private bool IsRisingOrFalling() { var verticalMomentum = VectorMath.ExtractDotVector(momentum, mover.transform.up); return (verticalMomentum.magnitude > 0.001f); } private void GroundContactLost() { var horizontalMomentumSpeed = VectorMath.RemoveDotVector(momentum, mover.transform.up).magnitude; var currentVelocity = momentum + Vector3.ClampMagnitude(savedMovementVelocity, Mathf.Clamp(motorVariables.MovementSpeed - horizontalMomentumSpeed, 0f, motorVariables.MovementSpeed)); var length = currentVelocity.magnitude; var velocityDirection = Vector3.zero; if (length != 0f) { velocityDirection = currentVelocity / length; } if (length >= motorVariables.MovementSpeed * motorVariables.AirControl) { length -= motorVariables.MovementSpeed * motorVariables.AirControl; } else { length = 0f; } momentum = velocityDirection * length; } private void GroundContactRegained(Vector3 collisionVelocity) { if (OnLand != null) OnLand(collisionVelocity); } private void JumpStart() { momentum += mover.transform.up * motorVariables.JumpSpeed; jumpStartTime = Time.time; if (OnJump != null) { OnJump(momentum); } } private void Crouch() { crouching = true; } private void UnCrouch() { crouching = false; } #region Teleports private void TeleportPlayerRoom(Vector3 desiredWorldPositionOfRoom, Quaternion desiredWordRotationOfRoom) { PlayerManager.Instance.transform.rotation = desiredWordRotationOfRoom; PlayerManager.Instance.transform.position = desiredWorldPositionOfRoom; } private void TeleportPlayerHead(Vector3 desiredWorldPositionOfCamera) { TeleportPlayerRoom(desiredWorldPositionOfCamera + (PlayerManager.Instance.transform.position - Camera.main.transform.position), PlayerManager.Instance.transform.rotation); } private void TeleportPlayerHead(Vector3 desiredWorldPositionOfCamera, float lookAtYEulerAngle) { if (PlayerSettingsManager.Instance.RoomSetup == RoomSetupEnum.Roomscale) { TeleportPlayerRoom(desiredWorldPositionOfCamera + (Quaternion.Euler(0f, lookAtYEulerAngle - Camera.main.transform.eulerAngles.y, 0f) * (PlayerManager.Instance.transform.position - Camera.main.transform.position)), Quaternion.Euler(0f, lookAtYEulerAngle - Camera.main.transform.localEulerAngles.y, 0f)); } else { TeleportPlayerRoom(desiredWorldPositionOfCamera + (Quaternion.Euler(0f, lookAtYEulerAngle - PlayerManager.Instance.transform.eulerAngles.y, 0f) * (PlayerManager.Instance.transform.position - Camera.main.transform.position)), Quaternion.Euler(0f, lookAtYEulerAngle, 0f)); } } #endregion } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.InputSystem; namespace VRBattleRoyale { public class InputManager : MonoBehaviour { private static InputManager instance; public static InputManager Instance { get { return instance; } } private Input input; private InputAction moveAction; private InputAction rotateAction; private InputAction jumpAction; private InputAction crouchAction; private InputAction moveInputOrientationAction; public Vector3 MoveInput { get { var movementInput = moveAction.ReadValue<Vector2>(); var orientationYEulerAngle = moveInputOrientationAction.ReadValue<Quaternion>().eulerAngles.y; var rotatedMoveInput = Quaternion.Euler(0f, orientationYEulerAngle, 0f) * new Vector3(movementInput.x, 0f, movementInput.y); if(rotatedMoveInput.magnitude > 1f) { rotatedMoveInput.Normalize(); } return rotatedMoveInput; } } public float RotationInput { get { return rotateAction.ReadValue<float>(); } } public bool JumpInput { get { return jumpAction.triggered; } } public bool CrouchInput { get { return crouchAction.triggered; } } #region Unity Life Cycle private void Awake() { if (instance != null) { #if UNITY_EDITOR DestroyImmediate(gameObject); #else Destroy(gameObject); #endif return; } instance = this; DontDestroyOnLoad(gameObject); input = new Input(); } private void OnEnable() { input.Enable(); if(PlayerSettingsManager.Instance) { PlayerSettingsManager.Instance.OnInputLayoutChanged += InputLayoutChanged; PlayerSettingsManager.Instance.OnMovementOrientationModeChanged += MovementOrientationModeChanged; } } private void Start() { InitializeInputActions(); } private void OnDisable() { input.Disable(); if (PlayerSettingsManager.Instance) { PlayerSettingsManager.Instance.OnInputLayoutChanged -= InputLayoutChanged; PlayerSettingsManager.Instance.OnMovementOrientationModeChanged -= MovementOrientationModeChanged; } } private void OnDestroy() { if (instance == this) { input.Disable(); input.Dispose(); instance = null; } } #endregion #region Event Listeners private void InputLayoutChanged() { InitializeInputActions(); } private void MovementOrientationModeChanged() { InitializeInputActions(); } #endregion private void InitializeInputActions() { if(PlayerSettingsManager.Instance == null || PlayerSettingsManager.Instance.InputLayout == InputLayoutEnum.Default) { moveAction = input.Gameplay.LeftMove; rotateAction = input.Gameplay.RightRotate; jumpAction = input.Gameplay.RightJump; crouchAction = input.Gameplay.RightCrouch; if (PlayerSettingsManager.Instance == null || PlayerSettingsManager.Instance.MovementOrientationMode == MovementOrientationModeEnum.Head) { moveInputOrientationAction = input.Gameplay.HMDRotation; } else { moveInputOrientationAction = input.Gameplay.LeftHandRotation; } } else { moveAction = input.Gameplay.RightMove; rotateAction = input.Gameplay.LeftRotate; jumpAction = input.Gameplay.LeftJump; crouchAction = input.Gameplay.LeftCrouch; if (PlayerSettingsManager.Instance == null || PlayerSettingsManager.Instance.MovementOrientationMode == MovementOrientationModeEnum.Head) { moveInputOrientationAction = input.Gameplay.HMDRotation; } else { moveInputOrientationAction = input.Gameplay.RightHandRotation; } } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace VRBattleRoyale { public static class QuaternionUtil { public static Vitruvius.Generated.Quaternion ConvertToSpatialOSQuaternion(UnityEngine.Quaternion quaternion) { return new Vitruvius.Generated.Quaternion(quaternion.x, quaternion.y, quaternion.z, quaternion.w); } public static UnityEngine.Quaternion ConvertToUnityQuaternion(Vitruvius.Generated.Quaternion quaternion) { return new UnityEngine.Quaternion(quaternion.X, quaternion.Y, quaternion.Z, quaternion.W); } } }
daff725e9426e63084922f2a69707013fa4851c0
[ "C#" ]
26
C#
Barrinsworth/vr-battle-royale
78c91b636b0548f1892c620e37799f9a6e4052cb
72cd87815b63606d5a26ce7e05035ad9647da868
refs/heads/master
<repo_name>leeteukki/StanFord_Facelt<file_sep>/Facelt/FaceViewController.swift // // ViewController.swift // Facelt // // Created by <NAME> on 2017. 7. 30.. // Copyright © 2017년 <NAME>. All rights reserved. // import UIKit class FaceViewController: UIViewController { }
31ad77f18e78eb6f5af7208a843cbae8a663b2c6
[ "Swift" ]
1
Swift
leeteukki/StanFord_Facelt
7a0b484d8d786c962aeea789234f825ec81df25b
1cbc6d7f5d93e28fc0a2b315e2dabc71b61a5cdf
refs/heads/master
<file_sep>import { LightningElement, api, track } from 'lwc'; export default class MultipleFileUpload extends LightningElement { @api minimumFilesCount;//The minimum number of files to be uploaded @api maximumFilesCount;//The maximum number of files that can be uploaded @api initFilesCount = 1;//The number of file uploader components that are loaded up on init @api customErrorMessage;//A custom error message to be displayed if the minimum files are not available @api accept;//Pass through attribute to the accept attribute of the SingleFileUpload component @api recordId;//Pass through attribute to the recordId attribute of the SingleFileUpload component @api disableDelete;//Pass through attribute to the disableDelete attribute of the SingleFileUpload component @api disableSoftDeleteForInitFile;//Pass through attribute to the disableSoftDeleteForInitFile attribute of the SingleFileUpload component @api instanceIdPrefix = "multiFile";//The prefix to be supplied for the instanceID attribute of the SingleFileUpload component @api initFilesList; @track filesList; @track showError; @track errorMessage; @track addButtonDisabled; @track containerCSS; fileIdsToSoftDelete; connectedCallback() { this.fileIdsToSoftDelete = []; this.loadEmptyTable(); this.addButtonDisabled = false; this.processFileRows(); } addRow(){ this.addFileRow(); this.processFileRows(); } removeRow(event){ let selectedItem = event.currentTarget; let index = selectedItem.dataset.record; this.filesList.splice(index, 1); this.checkAddButtonCondition(); } @api returnFileDetails(){ let retObj = []; var fileElems = this.template.querySelectorAll('c-single-file-upload'); for(let index = 0; index < fileElems.length; index++){ retObj.push(JSON.parse(JSON.stringify(fileElems[index].getFileDetails()))); } return retObj; } @api checkIfMinFilesFound(){ let filesUploadedCount = 0; for (let i = 0; i < this.filesList.length; i++) { let file = this.filesList[i]; if(file._fileDocumentId) filesUploadedCount++; } this.showError = filesUploadedCount < this.minimumFilesCount; if(this.showError){ this.containerCSS = 'slds-has-error'; if(this.customErrorMessage){ this.errorMessage = this.customErrorMessage; }else this.errorMessage = "A minimum of "+this.minimumFilesCount+" files need to be uploaded"; }else{ this.containerCSS = ''; } return this.showError; } checkAddButtonCondition(){ if(this.maximumFilesCount) this.addButtonDisabled = this.filesList.length >= this.maximumFilesCount; } loadEmptyTable(){ if(this.initFilesList) this.filesList = JSON.parse(JSON.stringify(this.initFilesList)); if(!this.filesList) this.filesList = [{}]; if(this.initFilesCount > this.maximumFilesCount) this.initFilesCount = this.maximumFilesCount; let filesToAdd = this.initFilesCount - this.filesList.length; for (let i = 0; i < filesToAdd; i++) { this.filesList.push({}); } for (let i = 0; i < this.filesList.length; i++) { let fl = this.filesList[i]; fl._fileDocumentId = fl.fileDocumentId; fl._fileName = fl.fileName; } this.checkAddButtonCondition(); } addFileRow(){ this.filesList.push({}); this.checkAddButtonCondition(); } handleFileChange(evt){ let actionType = evt.detail.actionType; let fileSeriesIndex = evt.currentTarget.dataset.fileIndex; if(actionType === 'NewFile'){ this.filesList[fileSeriesIndex]._fileDocumentId = evt.detail.fileDocumentId; this.filesList[fileSeriesIndex]._fileName = evt.detail.fileName; }else{ this.filesList[fileSeriesIndex]._fileDocumentId = null; this.filesList[fileSeriesIndex]._fileName = null; if(actionType === 'SoftDelete'){ this.fileIdsToSoftDelete.push(evt.detail.fileDocumentId); } } this.processFileRows(); } @api findSoftDeleteFiles(){ return this.fileIdsToSoftDelete; } processFileRows(){ for (let i = 0; i < this.filesList.length; i++) { let fl = this.filesList[i]; fl.allowRowDelete = ((i !== 0 ) && (fl._fileDocumentId == null)); fl.instanceId = this.instanceIdPrefix + i; } } }<file_sep>import { LightningElement, api, track } from 'lwc'; export default class ErrorMessageDisplay extends LightningElement { @api get errorObj(){ return this._errorObj; } set errorObj(value){ this.populateErrorDisplayObject(value); } @track _errorObj; populateErrorDisplayObject(errorObj){ this._errorObj = {}; if(errorObj){ this._errorObj = JSON.parse(JSON.stringify(errorObj)); } if(!this._errorObj.iconName) this._errorObj.iconName = "utility:warning"; if(!this._errorObj.iconAltText) this._errorObj.iconAltText = 'Error!'; if(!this._errorObj.title) this._errorObj.title = 'Error'; } }<file_sep>import { LightningElement, api, track } from 'lwc'; import deleteContentDocument from '@salesforce/apex/SingleFileUploadController.deleteContentDocument'; export default class SingleFileUpload extends LightningElement { @api instanceId; @api fileName; @api fileDocumentId; @api fileUploadedBy; @api fileUploadedDate; @api label; @api accept; @api recordId; @api disableDelete; @api disableSoftDeleteForInitFile; @track _fileName;// = file.name; @track _fileDocumentId;// = file.documentId; @track isFileLoaded; @track deleteFileOnSubmit; @track showError; @track errorMessage; @track ApexResponse; @track loadFinished; @track containerCSS; @track fileUploadedByAvailable; @track fileDownloadURL; @track fileDownloadTitle; fileChangeEvt; connectedCallback(){ this.initializeComponent(); } @api initializeComponent(){ this.fileUploadedByAvailable = false; this.loadFileVariables(); this.checkIfFileLoaded(); if(this.disableSoftDeleteForInitFile){ this.deleteFileOnSubmit = this.isFileLoaded; } this.ApexResponse = {}; this.loadFinished = true; } @api getFileDetails(){ let retObj = {}; retObj.fileName = this._fileName; retObj.fileDocumentId = this._fileDocumentId; return retObj; } loadFileVariables(){ this._fileName = this.fileName; this._fileDocumentId = this.fileDocumentId; } checkIfFileLoaded(){ if(this._fileDocumentId){ this.isFileLoaded = true; this.fileDownloadURL = '/sfc/servlet.shepherd/document/download/' +this._fileDocumentId; this.fileDownloadTitle = this._fileName == null ? 'Download' : this._fileName; }else{ this.isFileLoaded = false; } if(this.fileUploadedBy) this.fileUploadedByAvailable = true; } handleUploadFinished(event){ this.isFileLoaded = true; let files = event.detail.files; files.forEach((file) => { this._fileName = file.name; this._fileDocumentId = file.documentId; this.checkIfFileLoaded(); }); this.deleteFileOnSubmit = true; this.clearErrors(); this.fireActionEvent('NewFile'); } clearErrors(){ this.showError = false; } fireActionEvent(actionType){ const fileChangeEvt = new CustomEvent( 'filechange', { detail: { "actionType": actionType, "instanceId": this.instanceId, "fileName": this._fileName, "fileDocumentId": this._fileDocumentId } } ); this.dispatchEvent(fileChangeEvt); } deleteFile(){ if(this.deleteFileOnSubmit){ deleteContentDocument({ contentDocumentId: this._fileDocumentId}) .then((resp) => { this.ApexResponse = resp; if(!resp.isException){ this.fireActionEvent('HardDelete'); this.unloadFile(); } }) .catch(() => { //alert('Something went wrong...'); }); }else{ this.fireActionEvent('SoftDelete'); this.unloadFile(); } } @api markError(showError, errorMessage){ this.showError = showError; this.errorMessage = errorMessage; if(!this.errorMessage) this.errorMessage = 'Please upload a file'; if(this.showError){ this.containerCSS = 'slds-has-error'; }else{ this.containerCSS = ''; } } unloadFile(){ this._fileName = null; this._fileDocumentId = null; this.checkIfFileLoaded(); } }
2696a64d25477267d714e03b1134889fda2303e8
[ "JavaScript" ]
3
JavaScript
jerunjose/JerunScripts
3aeedf6f3fc30a67f1b517507e907232d7c7013c
5b53883991a9b88328717a7fb3de475cba07325c
refs/heads/master
<repo_name>achrefsaadouni/MedGo<file_sep>/submission1.js 'use strict'; const fs = require('fs'); const N=200000; var st = []; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.replace(/\s*$/, '') .split('\n') .map(str => str.replace(/\s*$/, '')); main(); }); function readLine() { return inputString[currentLine++]; } function update(idx,left,right,pos,val){ if (left>pos || right<pos) return; if (left==right && left==pos){ st[idx]=val; return; } var mid=parseInt((left+right)/2); update(idx*2,left,mid,pos,val); update(idx*2+1,mid+1,right,pos,val); if (st[(idx*2)]>st[(idx*2)+1]) st[idx]=st[(idx*2)]; else st[idx]=st[(idx*2)+1]; } //get the maximum value of the array in the given range (qleft-qright) function get(idx,left,right,qleft,qright){ if (left>qright || right<qleft) return 0; if (left>=qleft && right<=qright) return st[idx]; var mid=parseInt((left+right)/2); var x1=get(idx*2,left,mid,qleft,qright); var x2=get(idx*2+1,mid+1,right,qleft,qright) if (x1>x2) return x1; else return x2; } // Complete the minimumLoss function below. function minimumLoss(price , n) { for(var i=0;i<2*N;i++) st[i]=0; var v=[] for(var i=0;i<n;i++) v[i]={first : price[i], second : i}; v.sort(function(a, b){return a.first-b.first}); var ans=1e18; for(var i=0;i<n;i++){ var x=v[i]; update(1,0,n-1,x.second,x.first); var y=get(1,0,n-1,x.second+1,n-1); if (y!=0){ if (x.first-y<ans) ans=x.first-y; } } return ans ; } function main() { const ws = fs.createWriteStream(process.env.OUTPUT_PATH); const n = parseInt(readLine(), 10); const price = readLine().split(' ').map(priceTemp => parseInt(priceTemp, 10)); let result = minimumLoss(price , n); ws.write(result + "\n"); ws.end(); } <file_sep>/submission2.js 'use strict'; const fs = require('fs'); process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.replace(/\s*$/, '') .split('\n') .map(str => str.replace(/\s*$/, '')); main(); }); function readLine() { return inputString[currentLine++]; } /* Sort the array in ascending order and descending order as both meet the given requirement. Compare the sorted arrays to the original array and if the elements do not match perform the swap and count the swap opertions.Print the minimum value. */ // Complete the lilysHomework function below. function lilysHomework(arr) { var n = arr.length; var ans1=0,ans2=0; var copy=arr.slice(); var copy2=arr.slice(); copy.sort(function(a, b){return a-b}); var pos = []; for(var i=0;i<n;i++)pos[arr[i]]=i; for(var i=0;i<n;i++){ if(copy2[i]!=copy[i]){ ans1++; pos[copy2[i]]=pos[copy[i]]; copy2[i] = [copy2[pos[copy[i]]], copy2[pos[copy[i]]] = copy2[i]][0]; pos[copy[i]]=i; } } copy=arr.slice(); copy2=arr.slice(); copy.sort(function(a, b){return b-a}); for(var i=0;i<n;i++)pos[arr[i]]=i; for(var i=0;i<n;i++){ if(copy2[i]!=copy[i]){ ans2++; pos[copy2[i]]=pos[copy[i]]; copy2[i] = [copy2[pos[copy[i]]], copy2[pos[copy[i]]] = copy2[i]][0]; pos[copy[i]]=i; } } if (ans1>ans2)return ans2; else return ans1; } function main() { const ws = fs.createWriteStream(process.env.OUTPUT_PATH); const n = parseInt(readLine(), 10); const arr = readLine().split(' ').map(arrTemp => parseInt(arrTemp, 10)); let result = lilysHomework(arr); ws.write(result + "\n"); ws.end(); } <file_sep>/README.md # ces fichiers sont les solutions des problemes lié https://github.com/chrisrydahl/testApp/ # MedGo
abed29270184358d945d712483d43d6cfea86253
[ "JavaScript", "Markdown" ]
3
JavaScript
achrefsaadouni/MedGo
2d5680842a9b5982a83b0d2cc34c55d2dec706a4
0a937ca8358b715f0465b607874fb60e98f75e89
refs/heads/master
<file_sep>```py urlpatterns = patterns('', (r'^accounts', AccountsController.routes()), ) class AccountsController(BaseController): simple_actions = 'index profile'.split() @action('get', 'post', 'put', 'delete', 'patch') # CRUD - create, read, update, delete def login(self): if self._is_authenticated(): return self._redirect(to='.index') if self._request.POST.get('remember_me'): self._request.session.set_expiry(3 * 60 * 60) # 3 hours return self._auth_proxy(authentication_form=AccountLoginForm) @action def logout(self): return self._auth_proxy(next_page=self._reverse('#login')) ``` <file_sep># coding=utf-8 from dagny import Resource, action from dagny.utils import camel_to_underscore, resource_name from django.shortcuts import redirect, get_object_or_404 @action.RENDERER.html def render_html(action, resource): return resource.render_html(action) class BaseResource(Resource): template_path_prefix = '' model = None def get_label(self): return camel_to_underscore(resource_name(self)) def get_template_name(self, action, ext='.html'): return "%s%s/%s%s" % (self.template_path_prefix, self.get_label(), action.name, ext) def get_context(self): return {'Self': self, '_': self} def render_html(self, action): from coffin.shortcuts import render_to_response return render_to_response(self.get_template_name(action, ext='.haml'), self.get_context()) def redirect(self, to_action, *args, **kwargs): return redirect('%s#%s' % (resource_name(self), to_action), *args, **kwargs) @property def objects(self): return self.model.objects def get_object(self, id): return get_object_or_404(self.model, id=id) <file_sep># coding=utf-8 import logging import urllib def helper(func): from coffin.common import env env.globals[func.__name__] = func return func @helper def url_to(resource, action=None, **params): from django.core.urlresolvers import reverse try: extra = '' if isinstance(resource, basestring): if '.' in resource: name = resource if action and not isinstance(action, basestring): params['id'] = str(action.id) if params: for k, v in params.iteritems(): if isinstance(v, unicode): params[k] = v.encode('utf8') extra = '?' + urllib.urlencode(params) else: resource_name = resource[:-1] action = action or 'index' name = '%s.%s' % (resource_name, action) else: from . import utils resource_name = utils.to_underscore(resource.__class__.__name__) action = action or 'show' extra = '?' + urllib.urlencode(dict(id=resource.id)) name = '%s.%s' % (resource_name, action.replace('#', '')) return reverse(name) + extra except Exception as e: logging.error('Failed rendering url_to tag: %r', e) @helper def markdown(text): import jinja2 from .utils import markdown_urlize return jinja2.Markup(markdown_urlize(text)) <file_sep># coding=utf-8 from setuptools import setup, find_packages setup(name='rails', version='0.0a', download_url='<EMAIL>:andreif/django-rails.git', packages=find_packages(exclude=['_*']), author='<NAME>', author_email='<EMAIL>', description='Ruby on Rails workflow for Django', keywords='django rails', url='http://github.com/andreif/django-rails', license='MIT', install_requires=[], ) <file_sep># coding=utf-8 from django import template from django.core.urlresolvers import reverse import logging import urllib register = template.Library() @register.tag def url_to(resource, action=None): try: if isinstance(resource, basestring): resource_name = resource[:-1] action = action or 'index' extra = '' else: resource_name = resource.__class__.__name__.lower() action = action or 'show' extra = '?' + urllib.urlencode(dict(id=resource.id)) return reverse('%s.%s' % (resource_name, action)) + extra except Exception as e: logging.error('Failed rendering url_to tag: %r', e) <file_sep># coding=utf-8 import re from django.conf import settings from django.template import TemplateDoesNotExist from django.template.loader import find_template_loader template_source_loaders = None def get_template_source_loaders(): global template_source_loaders if template_source_loaders is None: loaders = [] for loader_name in settings.TEMPLATE_LOADERS: loader = find_template_loader(loader_name) if loader is not None: loaders.append(loader) template_source_loaders = tuple(loaders) return template_source_loaders def load_template_source(name, dirs=None): for loader in get_template_source_loaders(): try: return loader.load_template_source(template_name=name, template_dirs=dirs) except TemplateDoesNotExist: pass raise TemplateDoesNotExist(name) def make_data_dict(data): dic = {} def set_dic(d, keys, value): k = keys.pop(0) if keys: d.setdefault(k, {}) return set_dic(d[k], keys, value) else: d[k] = value for k in data.keys(): if k.endswith('[]'): v = data.getlist(k) else: v = data.get(k) set_dic(dic, k.split('-'), v) return dic def to_underscore(camelcase): return re.sub(r'(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', r'_\1', camelcase).lower().strip('_') try: from django.contrib.markup.templatetags.markup import markdown except ImportError: markdown = lambda x: x try: from django.utils.html import urlize except ImportError: urlize = lambda x: x def markdown_urlize(node): return markdown(urlize(node)).replace('href="www.', 'href="http://www.') def remove_indent(text): lines = text.split('\n') min_indent = None for i in range(0, len(lines)): if re.match(r'^\s*$', lines[i]): lines[i] = '' else: m = re.search(r'^(\s+)', lines[i]) if m: if min_indent is None or len(m.group(0)) < min_indent: min_indent = len(m.group(0)) if min_indent: for i in range(1, len(lines) - 1): if lines[i].startswith(' ' * min_indent): lines[i] = lines[i][min_indent:] return '\n'.join(lines).strip() <file_sep># coding=utf-8 import json from django.conf.urls import patterns, url from django.core.urlresolvers import reverse from django import http from django.views.generic import View import urllib import re from . import utils def action(*args, **kwargs): func = args[0] if len(args) == 1 and callable(args[0]) else None def decorator(fn): def wrapper(*args, **kwargs): return fn(*args, **kwargs) wrapper.responds_to = (None if func else args) or ['get', 'post'] wrapper.url = kwargs.get('url') return wrapper if func: return decorator(func) else: return decorator class Context(dict): def __setattr__(self, key, value): if isinstance(key, basestring) and key.startswith('_'): super(Context, self).__setattr__(key, value) else: self[key] = value def __getattribute__(self, item): try: return super(Context, self).__getattribute__(item) except AttributeError as e: if isinstance(item, basestring): return self.get(item) else: raise e def update(self, E=None, **F): super(Context, self).update(**F) return self def __call__(self, *args, **kwargs): if args: raise return self.update(**kwargs) class Session(object): def __init__(self, session): self._session = session def __getitem__(self, item): return self._session.__getitem__(item) def __setitem__(self, key, value): return self._session.__setitem__(key, value) def __setattr__(self, key, value): if isinstance(key, basestring) and key.startswith('_'): super(Session, self).__setattr__(key, value) else: self._session[key] = value def __getattr__(self, item): try: if isinstance(item, basestring) and item.startswith('_'): return self.__getattribute__(item) else: return self._session.__getattribute__(item) except AttributeError as e: if isinstance(item, basestring): return self._session.get(item) else: raise e def __call__(self, *args, **kwargs): if args: raise return self._session.update(kwargs) class Request(object): def __init__(self, request): self.request = request def is_ajax(self): return self.request.is_ajax() def is_post(self): return self.request.method == 'POST' def is_get(self): return self.request.method == 'GET' def is_authenticated(self): return self.request.user and self.request.user.is_authenticated() def is_staff(self): return self.is_authenticated() and self.request.user.is_staff def is_superuser(self): return self.is_authenticated() and self.request.user.is_superuser def data(self, *keys): if self.is_get(): data = self.request.GET elif self.is_post(): data = self.request.POST else: raise if keys: values = [data.get(k) for k in keys] if len(values) == 1: return values[0] else: return values else: return data def data_dict(self): return utils.make_data_dict(self.data()) class Router(object): def __init__(self, controller_class): if isinstance(controller_class, BaseController): self.controller_class = controller_class.__class__ else: self.controller_class = controller_class self.controller_name = self.controller_class._controller_name() def get_routes(self, prefix): self.prefix = prefix cls = self.controller_class actions = cls._actions() + cls.simple_actions routes = [self.get_route(name) for name in actions] if 'index' in actions: routes.append(self.get_route('index', regex=r'^/?$')) class urlconf_module(object): urlpatterns = patterns('', *routes) return urlconf_module, cls.app_name, cls.namespace #import collections #urlconf_module = collections.namedtuple('urlconf_module', 'urlpatterns') #return urlconf_module(urlpatterns = patterns('', *routes)), 'x', '' def get_view(self, name): def view(request, *args, **kwargs): return self.controller_class(request, name)._render(args=args, kwargs=kwargs) return view def get_route(self, name, regex=None): u = getattr(getattr(self.controller_class, name, None), 'url', None) u = u or r'%s(\.[a-z]+)?/?$' % name.replace('__', '/').replace('_', '-') return url( regex or r'^%s%s' % (self.prefix or '', u), self.get_view(name), name='%s.%s' % (self.controller_name, name), ) def reverse(self, url, args, kwargs): if '/' not in url: if url.startswith('.'): url = self.controller_name + url elif url.startswith('#'): url = self.controller_name + '.' + url[1:] url = reverse(url, args=args, kwargs=kwargs) return url class Renderer(object): allowed_extensions = ('html', 'haml') def __init__(self, controller): self.controller = controller def render_to_response(self, template_name): from coffin.shortcuts import render_to_response from coffin.template import RequestContext return render_to_response(template_name, self.controller.cx, RequestContext(self.controller.rq.request)) def find_template(self, template_name): from django.template import TemplateDoesNotExist for ext in self.allowed_extensions: try: utils.load_template_source(template_name + '.' + ext) return template_name + '.' + ext except TemplateDoesNotExist: continue class TemplateDoesNotExist(Exception): # standard exc fails due to missing traceback pass raise TemplateDoesNotExist(template_name + '.(%s)' % ', '.join(self.allowed_extensions)) class Inspector(object): def __init__(self, controller_class): self.controller_class = controller_class class ResponseError(Exception): pass class BaseController(View): simple_actions = [] template_name_prefix = '' app_name = None namespace = None def __init__(self, request, action): super(BaseController, self).__init__() self.cx = Context() self.rq = Request(request) self.ss = Session(request.session) self.router = Router(self.__class__) self.renderer = Renderer(self) self._current_action = action self.cx.current_action = action self.route_args = self.route_kwargs = None def _redirect(self, to='/', params=None, obj=None): if to == ':back': url = self.rq.request.META['HTTP_REFERER'] else: if to.startswith('#'): to = self._controller_name() + '.' + to[1:] url = self.router.reverse(to, args=self.route_args, kwargs=self.route_kwargs) if obj: params = params or {} params['id'] = obj.id if isinstance(params, dict): url += '?' + urllib.urlencode(params) elif params and hasattr(params, 'id'): url += '?' + urllib.urlencode(dict(id=params.id)) return http.HttpResponseRedirect(redirect_to=url) def _template(self, name=None): name = self.cx.action_template or name or self._current_action if '/' in name: template_name = name else: name = name or self._current_action name = name.replace('__', '/') template_name = '%s%s/%s' % (self.template_name_prefix, self._controller_name(), name) return self.renderer.find_template(template_name) def _setup_render(self): """ = builtin.str(1) = import.re.sub('1', '2', '1') """ import __builtin__ self.cx.builtin = __builtin__ self.cx.bi = __builtin__ #def _import(item, frm=None): # return __import__(item) class imp(object): def __getattribute__(self, item): return __import__(item) self.cx['import'] = imp() self.cx.imp = imp() def include_raw(path): import inspect from os.path import dirname, join import jinja2 try: fp = join(dirname(inspect.currentframe().f_back.f_back.f_code.co_filename), path) s = open(fp).read().decode('utf-8') return jinja2.Markup(s) except Exception: pass self.cx.include_raw = include_raw __import__('rails.helpers') # register helpers # id = self.rq.data('id') # if id: # self.cx.activation = DigitalActivation.objects.get(id=id) def _before_render(self): if getattr(self, 'staff_required', False) and not self.rq.is_staff(): return self._redirect('/admin') def _render(self, name=None, args=None, kwargs=None): if name and name.startswith('#'): name = name[1:] self.route_args = self.route_args or args or () self.route_args = [a or '' for a in self.route_args] self.route_kwargs = self.route_kwargs or kwargs or {} name = name or self._current_action self.cx( current_action=self._current_action, current_controller=self._controller_name(), title='%s | %s' % (self._controller_name(), name) ) if name in self._actions(): self._setup_render() try: response = self._before_render() or getattr(self, name)() except ResponseError as e: return e.message if isinstance(response, http.HttpResponse): return response elif name not in self.simple_actions: return http.HttpResponseNotFound('Unknown route') return self.renderer.render_to_response(self._template(name)) def abort(self, response): raise ResponseError(response) def _render_json(self, data): return http.HttpResponse(json.dumps(data), mimetype='application/json') def _render_error(self, status=403): return http.HttpResponse(status=status) def render(self, action): self.cx.update(action_template=action.replace('#', '')) @classmethod def _controller_name(cls): return re.sub(r'([A-Z]+)', '_\\1', cls.__name__).lower()[1:-11] @classmethod def _is_action(cls, name): return not name.startswith('_') and (hasattr(getattr(cls, name), 'responds_to') or getattr(cls, 'has_simple_actions', False)) @classmethod def _actions(cls): return [name for name in dir(cls) if cls._is_action(name)] @classmethod def routes(cls, prefix='/'): return Router(cls).get_routes(prefix) @classmethod def render_view(cls, name, request, *args, **kwargs): return Router(cls).get_view(name)(request, *args, **kwargs)
ab8b1b85fbdc0bf92e5f3697cccf6b55dd88f7e6
[ "Markdown", "Python" ]
7
Markdown
andreif/django-rails
85798fbc5f8003c756b2e61e90534e5da3a4fd88
5889da1572c7fcd6a6c17bef06f777abcfc2c5bb
refs/heads/main
<file_sep><!-- modal dialog ( edit profile ) --> <style> .premise-items { margin-bottom: 15px; } .thumnails-premise { border: 1px #08080759 solid; border-radius: 7px; width: 100%; display: block; cursor: pointer; height: 168px; width: 168px; } .thumnails-premise-valid { border: 1px solid #fd8a5c; box-shadow: 0px 0px 6px #ff4700a3; } </style> <div class="modal fade" id="editProfile" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Personal information</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <!-- Form --> <form id="form_profile" method='post' action='' enctype="multipart/form-data"> <div class="col-md-12 premise-items"> <?php $pic = Router::getSourcePath() . "images/" . $employee->Picuture_Employee; ?> <img id="thumnails_profile" browsid="profile" class="thumnails-premise" src="<?= $pic ?>" alt="image" style=""/> <input id="profile" name="profile" type="file" accept=".png, .jpg,.jpeg,.gif" style=""> <!-- <br> <label class="" style=" padding-top: 5px;">Profile Picture</label> --> </div> <div class="form-group row"> <div class="col-md-6"> <label for="firstname" class="col-form-label">ชื่อ:</label> <input type="text" class="form-control" id="firstname" name="Name_Employee" value="<?php echo $employee->getName_Employee() ?>" required="required"> </div> <div class="col-md-6"> <label for="surname" class="col-form-label">นามสกุล:</label> <input type="text" class="form-control" id="surname" name="Surname_Employee" value="<?php echo $employee->getSurname_Employee() ?>" required="required"> </div> </div> <div class="form-group"> <label for="username" class="col-form-label">ชื่อผู้ใช้:</label> <input type="text" class="form-control" id="username" name="Username_Employee" value="<?php echo $employee->getUsername_Employee() ?>" required="required"> </div> <a href="#" id="resetpassword_Profile" class="btn btn-primary btn-block"><i class="fa fa-key"></i> รีเซ็ตรหัสผ่าน</a> <div class="form-group" id="div_resetpassword_Profile" style="display:none;"> <label for="Password_Employee_Profile" id="lbl_Password_Employee_Profile" class="col-form-label">รหัสผ่าน:<span class="text-danger" >*</span></label> <!-- <input type="password" class="form-control" id="Password_Employee_Profile" name="Password_Employee_Profile" value="" > --> <div class="input-group" id="Password_Employee_Profile" required="required"> <input class="form-control" id="passEmProfile" name="Password_Employee_Profile" type="password"><br> <div class="input-group-append"> <a href="" class="input-group-text"><i class="fa fa-eye-slash" aria-hidden="true"></i></a> </div> </div> <label for="Password_Employee_Profile" id="lbl_Password_Employee_Profile" class="col-form-label">ยืนยันรหัสผ่าน:<span class="text-danger" >*</span></label> <div class="input-group" id="Password_Employee_Profile_Confirm" required="required"> <input class="form-control" name="Password_Employee_Profile_Confirm" data-rule-equalTo="#passEmProfile" type="password"> <div class="input-group-append"> <a href="" class="input-group-text"><i class="fa fa-eye-slash" aria-hidden="true"></i></a> </div> </div> <span class="error_replacement_profile"></span> </div> <!-- <div class="form-group" id="formgroup_currentpwd"> <label for="Password_Employee" class="col-form-label">Password:</label> <div class="input-group" id="show_hide_password" required="required"> <input class="form-control" id="Password_Employee" name="Password_Employee" value="<?php echo $employee->getCurrent_Password_Employee(); ?>" type="password" > <div class="input-group-append"> <a href="" class="input-group-text"><i class="fa fa-eye-slash" aria-hidden="true"></i></a> </div> </div> <span class="error_replacement_edit_profile"></span> </div> --> <div class="form-group"> <label for="email" class="col-form-label">อีเมล์:<span class="text-danger" >*</span></label> <input type="email" class="form-control" id="email" name="Email_Employee" value="<?php echo $employee->getEmail_Employee(); ?>" required="required"> </div> </form> </div> <div class="modal-footer"> <button type="button" onclick="editProfile()" class="btn btn-primary">ตกลง</button> <button type="button" class="btn btn-secondary" data-dismiss="modal">ยกเลิก</button> </div> </div> </div> </div><file_sep><?php class Sales { //------------- Properties private $ID_Excel; private $Date_Sales; private $ID_Company; private $Name_Company; private $ID_Employee; private $Result_Sales; private const TABLE = "sales"; //----------- Getters & Setters public function getID_Excel(): int { return $this->ID_Excel; } public function setID_Excel(int $ID_Excel) { $this->ID_Excel = $ID_Excel; } public function getDate_Sales(): string { return $this->Date_Sales; } public function setDate_Sales(string $Date_Sales) { $this->Date_Sales = $Date_Sales; } public function getID_Company(): int { return $this->ID_Company; } public function setID_Company(int $ID_Company) { $this->ID_Company = $ID_Company; } public function getName_Company(): string { return $this->Name_Company; } public function setName_Company(string $Name_Company) { $this->Name_Company; } public function getName_Employee(): string { return $this->Name_Employee; } public function setName_Employee(string $Name_Employee) { $this->Name_Employee; } public function getID_Employee(): string { return $this->ID_Employee; } public function setID_Employee(int $ID_Employee) { $this->ID_Employee = $ID_Employee; } public function getResult_Sales(): float { return $this->Result_Sales; } public function setResult_Sales(float $Result_Sales) { $this->Result_Sales = $Result_Sales; } //----------- CRUD public static function findAll(): array { $con = Db::getInstance(); //case: จัดการยอดขายเปลี่ยนไอดีบริษัทเป็นชื่อบริษัทเปลี่ยนไอดีพนักงานเป็นชื่อพนักงาน $query = "SELECT " . self::TABLE . ".* ,company.Name_Company,employee.Name_Employee FROM " . self::TABLE . " join company on " . self::TABLE . ".ID_Company=company.ID_Company join employee on " . self::TABLE . ".ID_Employee=employee.ID_Employee "; $stmt = $con->prepare($query); $stmt->setFetchMode(PDO::FETCH_CLASS, "Sales"); $stmt->execute(); $salesList = array(); while ($prod = $stmt->fetch()) { $salesList[$prod->getID_Excel()] = $prod; } return $salesList; } public static function findById(int $ID_Excel): ?Sales { $con = Db::getInstance(); $query = "SELECT * FROM " . self::TABLE . " WHERE ID_Excel = '$ID_Excel'"; $stmt = $con->prepare($query); $stmt->setFetchMode(PDO::FETCH_CLASS, "Sales"); $stmt->execute(); if ($prod = $stmt->fetch()) { return $prod; } return null; } # จัดการยอดขาย ( เพิ่มยอดขาย ) public function create_sales(array $params) { $con = Db::getInstance(); $values = ""; $columns = ""; foreach ($params as $prop => $val) { # ถ้า column แรกไม่ต้องเติมลูกน้ำ คอลัมน์อื่นเติมลูกน้ำ $columns = empty($columns) ? $columns .= $prop : $columns .= "," . $prop; $values .= "'$val',"; } $values = substr($values, 0, -1); $query = "INSERT INTO " . self::TABLE . " ({$columns}) VALUES ($values)"; //return $query; # execute query if ($con->exec($query)) { $this->ID_Excel = $con->lastInsertId(); return array("status" => true); } else { $message = "มีบางอย่างผิดพลาด , กรุณาตรวจสอบข้อมูล "; return array("status" => false, "message" => $message); } } # จัดการยอดขาย ( เพิ่มยอดขาย excel ) public function create_sales_at_once(array $params) { error_reporting(0); // Turn off all error reporting $con = Db::getInstance(); // turn off auto commit (ปิดคำสั่งสำหรับการยืนยันการเปลี่ยนแปลงข้อมูลที่เกิดขึ้น) $con->beginTransaction(); foreach ($params as $k => $v) { $values = ""; $columns = ""; foreach ($v as $prop => $val) { # ถ้า column แรกไม่ต้องเติมลูกน้ำ คอลัมน์อื่นเติมลูกน้ำ .. if($prop == "Date_Sales"){ // convert format from day/month/year to year-month-day $explode_string = explode("/" , $val); $date = $explode_string[0]; $month= $explode_string[1]; $year = intval($explode_string[2]) - 543; // แปลงพศ. เป็น คศ //echo date("Y-m-d", strtotime("{$val}"));exit(); $val = date("Y-m-d", strtotime("{$year}-{$month}-{$date}")); } $columns = empty($columns) ? $columns .= $prop : $columns .= "," . $prop; $values .= "'$val',"; } # insert ลง db $values = substr($values, 0, -1); $query = "INSERT INTO " . self::TABLE . "({$columns}) VALUES ($values)"; //echo $query;exit(); # execute query if ($con->exec($query)) { # do something } else { # rollback when got error $con->rollBack(); $message = "มีบางอย่างผิดพลาด , กรุณาตรวจสอบข้อมูล "; return array("status" => false, "message" => $message); } } # commit $con->commit(); return array("status" => true); } public function file_log(string $file_name, int $id) { $query = "UPDATE file_log SET file_name = '{$file_name}' where id = {$id} "; //echo $query;exit(); $con = Db::getInstance(); if ($con->exec($query)) { return array("status" => true); } } # แก้ไข ยอดขาย public function edit_sales(array $params, string $ID_Excel) { $query = "UPDATE " . self::TABLE . " SET "; foreach ($params as $prop => $val) { if (!empty($val)) { $query .= " $prop='$val',"; } } $query = substr($query, 0, -1); $query .= " WHERE ID_Excel = '" . $ID_Excel . "'"; //echo $query;exit(); $con = Db::getInstance(); if ($con->exec($query)) { return array("status" => true); } else { return array("status" => false); } } # ลบ ยอดขาย public function delete_sales($ID_Excel) { $query = "DELETE FROM " . self::TABLE . " WHERE ID_Excel = '{$ID_Excel}' "; $con = Db::getInstance(); if ($con->exec($query)) { return array("status" => true); } else { return array("status" => false); } } } ?> <file_sep><?php class Db { private static $instance = NULL; private static $dsn = "mysql:dbname=project;host=localhost"; private static $user = "root"; private static $pass = ""; private function __construct() { } private function __clone() { } public static function getInstance() { if (!isset(self::$instance)) { self::$instance = new PDO(self::$dsn, self::$user, self::$pass); self::$instance->query("SET NAMES UTF8"); } return self::$instance; } }<file_sep><?php header("Location: " . Router::getSourcePath() . "index.php?controller=News&action=show_news_status"); ?> <file_sep><?php class AwardController { /** * handleRequest จะทำการตรวจสอบ action และพารามิเตอร์ที่ส่งเข้ามาจาก Router * แล้วทำการเรียกใช้เมธอดที่เหมาะสมเพื่อประมวลผลแล้วส่งผลลัพธ์กลับ * * @param string $action ชื่อ action ที่ผู้ใช้ต้องการทำ * @param array $params พารามิเตอร์ที่ใช้เพื่อในการทำ action หนึ่งๆ */ public function handleRequest(string $action = "index", array $params) { switch ($action) { case "index": $this->index(); break; case "manage_award" : $this->$action(); break; case "create_award": $FILE_IMG = isset($params["FILES"]["award_pic"]) ? $params["FILES"]["award_pic"] : ""; $result = $this->$action($params["POST"], $FILE_IMG); echo $result; break; case "findAwardbyID_Award" : $ID_Award = isset($params["POST"]["ID_Award"]) ? $params["POST"]["ID_Award"] : ""; if (!empty($ID_Award)) { $result = $this->$action($ID_Award); echo $result; } break; case "edit_award" : $FILE_IMG = isset($params["FILES"]) ? $params["FILES"] : ""; $Params= isset($params["POST"]) ? $params["POST"] : ""; $ID_Award = isset($params["GET"]["ID_Award"]) ? $params["GET"]["ID_Award"] : ""; $result = $this->$action($params["POST"] ,$FILE_IMG, $ID_Award); echo $result; break; case "delete_award": $params = isset($params["GET"]["ID_Award"]) ? $params["GET"]["ID_Award"] : ""; $result = $this->$action($params); // print_r($params); echo $result; break; case "show_award_status": session_start(); $employee = $_SESSION["employee"]; if ($employee->getUser_Status_Employee() == "Admin") { include Router::getSourcePath() . "views/index_admin.inc.php"; } else if ($employee->getUser_Status_Employee() == "Sales") { # retrieve data $awardList = Award::fetchAllwithInner($employee->getID_Employee()); $countAllAward = Award::fetchCountAll($employee->getID_Employee()); include Router::getSourcePath() . "views/sales/index_award.inc.php"; } else if ($employee->getUser_Status_Employee() == "User") { # retrieve data $awardList = Award::fetchAllwithInner($employee->getID_Employee()); $countAllAward = Award::fetchCountAll($employee->getID_Employee()); include Router::getSourcePath() . "views/user/index_award.inc.php"; } break; case "update_status_award": session_start(); $employee = $_SESSION['employee']; $ID_Award = isset($params["GET"]["ID_Award"]) ? $params["GET"]["ID_Award"] : ""; if ($employee->getUser_Status_Employee() == "Admin") { include Router::getSourcePath() . "views/index_admin.inc.php"; } else if ($employee->getUser_Status_Employee() == "Sales") { # retrieve data $award = Award::update_award_status($employee->getID_Employee(), $ID_Award); $awardList = Award::fetchAllwithInner($employee->getID_Employee()); include Router::getSourcePath() . "views/sales/redirect_index_award.inc.php"; } else if ($employee->getUser_Status_Employee() == "User") { # retrieve data $award = Award::update_award_status($employee->getID_Employee(), $ID_Award); $awardList = Award::fetchAllwithInner($employee->getID_Employee()); include Router::getSourcePath() . "views/user/redirect_index_award.inc.php"; } break; default: break; } } private function create_award($params, $FILE_IMG) { $access_award = new Award(); // # สร้างข่าวสาร $awardid = $access_award->geneateDateTimemd() ; $award_title = $params["Tittle_Award"] ; $award_filename = !empty($FILE_IMG) ? $access_award->generatePictureFilename($FILE_IMG['name'][0], $award_title) : "" ; $award_datetime = $access_award->geneateDateTime(); $locate_img = ""; $award_ID_Employee = $params["ID_Employee"]; if (!empty($FILE_IMG) && !empty($FILE_IMG['name'])) { $name_file = $FILE_IMG['name'][0]; $name_file_type = explode('.',$name_file)[1] ; $tmp_name = $FILE_IMG['tmp_name'][0]; $locate_img = Router::getSourcePath() . "images/" . $award_filename . ".".$name_file_type; // copy original file to destination file move_uploaded_file($tmp_name, $locate_img); } $access_award_params = array( "ID_Award" => $awardid, "Tittle_Award" => $award_title, "Picture_Award" => $locate_img, "Date_Award"=> $award_datetime, "ID_Employee" => $award_ID_Employee, ); $result = $access_award->create_award( $access_award_params ); return json_encode($result); } private function findAwardbyID_Award($findbyID_Award) { $award = Award::findAward_byID($findbyID_Award);//echo json_encode($employee); // echo json_encode(array("data" => $data_sendback)); $data_sendback = array( "ID_Award" => $award->getID_Award(), "Tittle_Award" => $award->getTittle_Award(), "Picture_Award" => $award->getPicture_Award(), "Date_Award" => $award->getDate_Award(), "ID_Employee" => $award->getID_Employee(), ); echo json_encode(array("data" => $data_sendback)); } private function edit_award($params, $FILE_IMG, $ID_Award) { // # สร้างข่าวสารร $access_award = new Award(); $awardid = $ID_Award ; $award_title = $params["Tittle_Award"] ; $award_datetime = $access_award->geneateDateTime(); $locate_img = ""; // print_r('hello world'. ' ' . $access_news->generatePictureFilename($FILE_IMG['profile_news']['name'][0], $message_title)); $award_filename = !empty($FILE_IMG) ? $access_award->generatePictureFilename($FILE_IMG['award_pic']['name'][0], $award_title) : "" ; if (!empty($FILE_IMG) && !empty($FILE_IMG['award_pic']['name'])) { $name_file = $FILE_IMG['award_pic']['name'][0]; $name_file_type = explode('.',$name_file)[1] ; $tmp_name = $FILE_IMG['award_pic']['tmp_name'][0]; $locate_img = Router::getSourcePath() . "images/" . $award_filename . ".".$name_file_type; // copy original file to destination file move_uploaded_file($tmp_name, $locate_img); } $access_award_params = array( "ID_Award" => $awardid, "Tittle_Award" => $award_title, "Picture_Award" => $locate_img, "Date_Award"=> $award_datetime, ); $result = $access_award->update_award( $access_award_params ); return json_encode($result); } private function delete_award($params) { $access_award = new Award(); $result = $access_award->delete_award( $params ); // print_r($result); return json_encode($result); } private function error_handle(string $message) { $this->index($message); } // ควรมีสำหรับ controller ทุกตัว private function index($message = null) { session_start(); $employee = $_SESSION["employee"]; include Router::getSourcePath() . "views/index_admin.inc.php"; } //หน้าจัดการรางวัล private function manage_award() { session_start(); $employee = $_SESSION["employee"]; # retrieve data $employeeList = Employee::findAll(); $awardList = Award::fetchAll(); include Router::getSourcePath() . "views/admin/manage_award.inc.php"; } }<file_sep><?php class Promotion { //------------- Properties private $ID_Promotion; private $Name_Promotion; private $Unit_Promotion; private $Price_Unit_Promotion; private const TABLE = "promotion"; //----------- Getters & Setters public function getID_Promotion(): int { return $this->ID_Promotion; } public function setID_Promotion(int $ID_Promotion) { $this->ID_Promotion = $ID_Promotion; } public function getName_Promotion() : string { return $this->Name_Promotion; } public function setName_Promotion(string $Name_Promotion) { $this->Name_Promotion = $Name_Promotion; } public function getUnit_Promotion() : int { return $this->Unit_Promotion; } public function setUnit_Promotion(int $Unit_Promotion) { $this->Unit_Promotion = $Unit_Promotion; } public function getPrice_Unit_Promotion() : float { return $this->Price_Unit_Promotion; } public function setPrice_Unit_Promotion(float $Price_Unit_Promotion) { $this->Price_Unit_Promotion = $Price_Unit_Promotion; } //----------- CRUD public static function findAll(): array { $con = Db::getInstance(); $query = "SELECT * FROM " . self::TABLE; $stmt = $con->prepare($query); $stmt->setFetchMode(PDO::FETCH_CLASS, "Promotion"); $stmt->execute(); $promotionList = array(); while ($prod = $stmt->fetch()) { $promotionList[$prod->getID_Promotion()] = $prod; } return $promotionList; } public static function findById(string $ID_Promotion): ?Promotion { $con = Db::getInstance(); $query = "SELECT * FROM " . self::TABLE . " WHERE ID_Promotion = '$ID_Promotion'"; $stmt = $con->prepare($query); $stmt->setFetchMode(PDO::FETCH_CLASS, "Promotion"); $stmt->execute(); if ($prod = $stmt->fetch()) { return $prod; } return null; } # จัดการสินค้าส่งเสริมการขาย ( เพิ่มสินค้าส่งเสริมการขาย ) public function create_promotion(array $params) { $con = Db::getInstance(); $values = ""; $columns = ""; foreach ($params as $prop => $val) { # ถ้า column แรกไม่ต้องเติมลูกน้ำ คอลัมน์อื่นเติมลูกน้ำ $columns = empty($columns) ? $columns .= $prop : $columns .= "," . $prop; $values .= "'$val',"; } $values = substr($values, 0, -1); $query = "INSERT INTO " . self::TABLE . "({$columns}) VALUES ($values)"; # execute query if ($con->exec($query)) { return array("status" => true); } else { $message = "มีบางอย่างผิดพลาด , กรุณาตรวจสอบข้อมูล "; return array("status" => false, "message" => $message); } } # จัดการสินค้าส่งเสริมการขาย ( เพิ่มสินค้าส่งเสริมการขาย excel ) public function create_promotion_at_once(array $params) { $con = Db::getInstance(); // turn off auto commit (ปิดคำสั่งสำหรับการยืนยันการเปลี่ยนแปลงข้อมูลที่เกิดขึ้น) $con->beginTransaction(); foreach ($params as $k => $v) { $values = ""; $columns = ""; foreach ($v as $prop => $val) { # ถ้า column แรกไม่ต้องเติมลูกน้ำ คอลัมน์อื่นเติมลูกน้ำ .. $columns = empty($columns) ? $columns .= $prop : $columns .= "," . $prop; $values .= "'$val',"; } # insert ลง db $values = substr($values, 0, -1); $query = "INSERT INTO " . self::TABLE . "({$columns}) VALUES ($values)"; //echo $query;exit(); # execute query if ($con->exec($query)) { # do something } else { # rollback when got error $con->rollBack(); $message = "มีบางอย่างผิดพลาด , กรุณาตรวจสอบข้อมูล "; return array("status" => false, "message" => $message); } } # commit $con->commit(); return array("status" => true); } public function file_log(string $file_name, int $id) { $query = "UPDATE file_log SET file_name = '{$file_name}' where id = {$id} "; //echo $query;exit(); $con = Db::getInstance(); if ($con->exec($query)) { return array("status" => true); } } # แก้ไขสินค้าส่งเสริมการขาย public function edit_promotion(array $params, string $ID_Promotion) { $query = "UPDATE " . self::TABLE . " SET "; foreach ($params as $prop => $val) { if (!empty($val)) { $query .= " $prop='$val',"; } } $query = substr($query, 0, -1); $query .= " WHERE ID_Promotion = '" . $ID_Promotion . "'"; //echo $query;exit(); $con = Db::getInstance(); if ($con->exec($query)) { return array("status" => true); } else { return array("status" => false); } } # ลบสินค้าส่งเสริมการขาย public function delete_promotion($ID_Promotion) { $query = "DELETE FROM " . self::TABLE . " WHERE ID_Promotion = '{$ID_Promotion}' "; $con = Db::getInstance(); if ($con->exec($query)) { return array("status" => true); } else { return array("status" => false); } } } ?><file_sep><div class="modal fade" id="companymanageModal" tabindex="-1" role="dialog" aria-labelledby="companymanageModalDialog" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="companymanageTitle"></h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <!-- Form --> <form id="form_companymanage" method='post' action='' enctype="multipart/form-data"> <!-- <input type="hidden" name="ID_Company" value="" /> --> <div class="form-group" id="div_idcompany"> <!-- <label for="ID_Company" class="col-form-label">ไอดีบริษัทลูกค้า:</label>--> <!-- <input type="text" class="form-control" id="ID_Company" name="ID_Company" value="" required="required" > --> </div> <div class="form-group "> <label for="Name_Company" class="col-form-label">ชื่อบริษัท:<span class="text-danger" >*</span></label> <input type="text" class="form-control" id="Name_Company" name="Name_Company" value="" required="required"> </div> <div class="form-group"> <label for="Address_Company" class="col-form-label">ที่อยู่บริษัท:<span class="text-danger" >*</span></label> <input type="text" class="form-control" id="Address_Company" name="Address_Company" value="" required="required"> </div> <div class="form-group"> <label for="PROVINCE_ID" class="col-form-label">จังหวัด:<span class="text-danger" >*</span></label> <select class="form-control" name="PROVINCE_ID" id="province"> <option value="" selected disabled>-กรุณาเลือกจังหวัด-</option> <?php foreach ($provinceList as $province) { ?> <option value="<?php echo $province->getPROVINCE_ID(); ?>"><?php echo $province->getPROVINCE_NAME(); ?></option> <?php } ?> </select> </div> <div class="form-group"> <label for="AMPHUR_ID" class="col-form-label">อำเภอ:<span class="text-danger" >*</span></label> <select class="form-control" name="AMPHUR_ID" id="amphure_id"> <option value="" selected disabled>-กรุณาเลือกอำเภอ-</option> <?php foreach ($amphurList as $amphur) { ?> <option value="<?php echo $amphur->getAMPHUR_ID();?>"><?php echo $amphur->getAMPHUR_NAME(); ?></option> <?php } ?> </select> </div> <div class="form-group"> <label for="Tel_Company" class="col-form-label">เบอร์บริษัท:<span class="text-danger" >*</span></label> <input type="tel" class="form-control" id="Tel_Company" name="Tel_Company" value="" required="required"> </div> <div class="form-group"> <label for="Email_Company" class="col-form-label">อีเมล์บริษัท:<span class="text-danger" >*</span></label> <input type="email" class="form-control" id="Email_Company" name="Email_Company" value="" required="required"> </div> <div class="form-group"> <label for="Tax_Number_Company" class="col-form-label">เลขผู้เสียภาษี:<span class="text-danger" >*</span></label> <input type="tel" class="form-control" id="Tax_Number_Company" name="Tax_Number_Company" value="" required="required"> </div> <div class="form-group"> <label for="Credit_Limit_Company" class="col-form-label">วงเงินสูงสุด:<span class="text-danger" >*</span></label> <input type="number" class="form-control" id="Credit_Limit_Company" name="Credit_Limit_Company" value="" min='0' required="required"> </div> <div class="form-group"> <label for="Credit_Term_Company" class="col-form-label">เครดิตเทอม:<span class="text-danger" >*</span></label> <input type="text" class="form-control" id="Credit_Term_Company" name="Credit_Term_Company" value="" required="required"> </div> <div class="form-group"> <label for="Cluster_Shop" class="col-form-label">คลัสเตอร์:<span class="text-danger" >*</span></label> <select name="Cluster_Shop" class="form-control" id="Cluster_Shop"> <option value="ภาครัฐ">ภาครัฐ</option> <option value="ภาคเอกชน">ภาคเอกชน</option> <option value="รัฐวิสาหกิจ">รัฐวิสาหกิจ</option> </select> </div> <div class="form-group"> <label for="Contact_Name_Company" class="col-form-label">ชื่อที่ติดต่อ:</label> <input type="text" class="form-control" id="Contact_Name_Company" name="Contact_Name_Company" value=""> </div> <div class="form-group"> <label for="IS_Blacklist" class="col-form-label">บัญชีดำ:<span class="text-danger" >*</span></label> <select name="IS_Blacklist" class="form-control" id="IS_Blacklist"> <option value="ใช่">ใช่</option> <option value="ไม่ใช่">ไม่ใช่</option> </select> </div> <div class="form-group"> <label for="Cause_Blacklist" class="col-form-label">สาเหตุที่ติดบัญชีดำ:</label> <input type="text" class="form-control" id="Cause_Blacklist" name="Cause_Blacklist" value=""> </div> </form> </div> <div class="modal-footer"> <a href="#" id="button_companymanageModal" onclick="onaction_createorupdate()" data-status="" data-id="" class="btn btn-primary">ตกลง</a> <button type="button" class="btn btn-secondary" data-dismiss="modal">ยกเลิก</button> </div> </div> </div> </div><file_sep><?php /** PHPExcel */ require_once Router::getSourcePath() . 'library/PHPExcel-1.8/Classes/PHPExcel.php'; /** PHPExcel_IOFactory - Reader */ include Router::getSourcePath() . 'library/PHPExcel-1.8/Classes/PHPExcel/IOFactory.php'; class Excel extends PHPExcel { public function __construct() { } }<file_sep><?php class PromotionController { /** * handleRequest จะทำการตรวจสอบ action และพารามิเตอร์ที่ส่งเข้ามาจาก Router * แล้วทำการเรียกใช้เมธอดที่เหมาะสมเพื่อประมวลผลแล้วส่งผลลัพธ์กลับ * * @param string $action ชื่อ action ที่ผู้ใช้ต้องการทำ * @param array $params พารามิเตอร์ที่ใช้เพื่อในการทำ action หนึ่งๆ */ public function handleRequest(string $action = "index", array $params) { switch ($action) { case "index": $this->index(); break; case "manage_promotion" : $this->$action(); break; case "create_promotion" : $result = $this->$action($params["POST"]); echo $result; break; case "edit_promotion" : $ID_Promotion = isset($params["GET"]["ID_Promotion"]) ? $params["GET"]["ID_Promotion"] : ""; $result = $this->$action($params["POST"], $ID_Promotion); echo $result; break; case "delete_promotion": $result = $this->$action($params["POST"]["ID_Promotion"]); echo $result; break; case "findbyID_Promotion": $ID_Promotion = isset($params["POST"]["ID_Promotion"]) ? $params["POST"]["ID_Promotion"] : ""; if (!empty($ID_Promotion)) { $result = $this->$action($ID_Promotion); echo $result; } break; default: break; } } private function create_promotion($params) { # สร้างสินค้าส่งเสริมการขาย $access_promotion = new Promotion(); $promotion_result = $access_promotion->create_promotion( $params ); return json_encode($promotion_result); } private function edit_promotion($params, $ID_Promotion) { # อัปเดตสินค้าส่งเสริมการขาย $access_promotion = new Promotion(); $promotion_result = $access_promotion->edit_promotion( $params, $ID_Promotion ); echo json_encode($promotion_result); } private function delete_promotion($ID_Promotion) { # ลบสินค้าส่งเสริมการขาย $access_promotion = new Promotion(); $promotion_result = $access_promotion->delete_promotion( $ID_Promotion ); return json_encode($promotion_result); } private function findbyID_Promotion(string $ID_Promotion) { $promotion = Promotion::findById($ID_Promotion);//echo json_encode($sales); $data_sendback = array( "ID_Promotion" => $promotion->getID_Promotion(), "Name_Promotion" => $promotion->getName_Promotion(), "Unit_Promotion" => $promotion->getUnit_Promotion(), "Price_Unit_Promotion" => $promotion->getPrice_Unit_Promotion(), ); echo json_encode(array("data" => $data_sendback)); } private function error_handle(string $message) { $this->index($message); } // ควรมีสำหรับ controller ทุกตัว private function index($message = null) { session_start(); $employee = $_SESSION["employee"]; include Router::getSourcePath() . "views/index_admin.inc.php"; } //หน้าจัดการสินค้าส่งเสริมการขาย private function manage_promotion($params = null) { session_start(); $employee = $_SESSION["employee"]; # retrieve data $promotionList = Promotion::findAll(); include Router::getSourcePath() . "views/admin/manage_promotion.inc.php"; } }<file_sep><?php class Province { //------------- Properties private $PROVINCE_ID; private $PROVINCE_CODE; private $PROVINCE_NAME; private const TABLE = "province"; //----------- Getters & Setters public function getPROVINCE_ID() : int { return $this->PROVINCE_ID; } public function setPROVINCE_ID(int $PROVINCE_ID) { $this->PROVINCE_ID = $PROVINCE_ID; } public function getPROVINCE_CODE() : string { return $this->PROVINCE_CODE; } public function setPROVINCE_CODE(string $PROVINCE_CODE) { $this->PROVINCE_CODE = $PROVINCE_CODE; } public function getPROVINCE_NAME() : string { return $this->PROVINCE_NAME; } public function setPROVINCE_NAME(string $PROVINCE_NAME) { $this->PROVINCE_NAME = $PROVINCE_NAME; } //----------- CRUD public static function findAll(): array { $con = Db::getInstance(); $query = "SELECT * FROM " . self::TABLE; $stmt = $con->prepare($query); $stmt->setFetchMode(PDO::FETCH_CLASS, "Province"); $stmt->execute(); $provinceList = array(); while ($prod = $stmt->fetch()) { $provinceList[$prod->getPROVINCE_ID()] = $prod; } return $provinceList; } public static function findById(int $PROVINCE_ID): ?Province { $con = Db::getInstance(); $query = "SELECT * FROM " . self::TABLE . " WHERE PROVINCE_ID = '$PROVINCE_ID'"; $stmt = $con->prepare($query); $stmt->setFetchMode(PDO::FETCH_CLASS, "Province"); $stmt->execute(); if ($prod = $stmt->fetch()) { return $prod; } return null; } } <file_sep><?php class Award { //------------- Properties private $ID_Award; private $Tittle_Award; private $Picture_Award; private $Date_Award; private $ID_Employee; private $fullname_employee; private $status; private const TABLE = "award"; //----------- Getters & Setters public function getStatus(): int { return $this->status; } public function setStatus(int $status) { $this->status = $status; } // ---- id Award public function getID_Award(): int { return $this->ID_Award; } public function setID_Award(int $ID_Award) { $this->getID_Award = $getID_Award; } // --- title Award public function getTittle_Award(): string { return $this->Tittle_Award; } public function setTittle_Award(string $Tittle_Award) { $this->getTittle_Award = $getTittle_Award; } // --- picture Award public function getPicture_Award(): string { return $this->Picture_Award; } public function setPicture_Award(string $Picture_Award) { $this->getPicture_Award = $getPicture_Award; } // --- date Award public function getDate_Award(): string { return $this->Date_Award; } public function setDate_Award(string $Date_Award) { $this->getDate_Award = $getDate_Award; } public function getID_Employee() : string { return $this->ID_Employee; } public function setID_Employee(string $ID_Employee) { $this->getID_Employee = $ID_Employee; } public function getFullname_employee() : string { return $this->fullname_employee; } public function setFullname_employee(string $fullname_employee) { $this->getFullname_employee = $fullname_employee; } //CRUD public static function fetchCountAll($emp_id): array { $con = Db::getInstance(); $query = "select count(*) from award_status where status =0 and ID_Employee = '".$emp_id."'"; $stmt = $con->prepare($query); #$stmt->setFetchMode(PDO::FETCH_CLASS, "Message"); $stmt->execute(); #$list = array(); #while ($prod = $stmt->fetch()) { # $list[$prod->getID_Message()] = $prod; #} $prod = $stmt->fetch(); return $prod; #return $list; } public static function fetchAll(): array { $con = Db::getInstance(); $query = "SELECT " . self::TABLE . ".*,employee.ID_Employee, concat(employee.Name_Employee, ' ',employee.Surname_Employee) as fullname_employee FROM " . self::TABLE . " LEFT JOIN employee ON " . self::TABLE . ".ID_Employee = employee.ID_Employee " ; $stmt = $con->prepare($query); $stmt->setFetchMode(PDO::FETCH_CLASS, "award"); $stmt->execute(); $list = array(); while ($prod = $stmt->fetch()) { $list[$prod->getID_Award()] = $prod; } return $list; } public static function fetchAllwithInner($emp_id): array { $con = Db::getInstance(); #$query = "select * from award inner join award_status on award_status.ID_Award = award.ID_Award where award_status.ID_Employee = 's0001'"; $query = "select *, employee.Name_Employee as fullname_employee from award inner join award_status on award_status.ID_Award = award.ID_Award inner join employee on award.ID_Employee = employee.ID_Employee where award_status.ID_Employee = '".$emp_id."'"; $stmt = $con->prepare($query); $stmt->setFetchMode(PDO::FETCH_CLASS, "award"); $stmt->execute(); $list = array(); while ($prod = $stmt->fetch()) { $list[$prod->getID_Award()] = $prod; } return $list; } public static function findAward_byID($ID_Award): ?Award { $con = Db::getInstance(); $query = "SELECT * FROM " . self::TABLE . " WHERE ID_Award = '$ID_Award'"; $stmt = $con->prepare($query); $stmt->setFetchMode(PDO::FETCH_CLASS, "award"); $stmt->execute(); if ($prod = $stmt->fetch()) { return $prod; } return null; } public static function generateIDAward($title_award) { $awardid = self::geneateDateTimemd() ; return md5(uniqid($awardid, true)) ; } public static function geneateDateTimemd() { return Date("YmdHis") ; } public static function geneateDateTime() { return date("Y-m-d H:i:s") ; } public static function generatePictureFilename($imagename, $titleaward) { $award_picture_filename = "$imagename"."$titleaward".self::geneateDateTimemd() ; return md5(uniqid($award_picture_filename, true)) ; } // save data into database public static function create_award($awardModel) { $con = Db::getInstance(); $values = ""; $columns = ""; foreach ($awardModel as $prop => $val) { # ถ้า column แรกไม่ต้องเติมลูกน้ำ คอลัมน์อื่นเติมลูกน้ำ $columns = empty($columns) ? $columns .= $prop : $columns .= "," . $prop; $values .= "'$val',"; } $values = substr($values, 0, -1); $query = "INSERT INTO " . self::TABLE . "({$columns}) VALUES ($values)"; # execute query if ($con->exec($query)) { $emp = new Employee(); $result = $emp->findAll(); # เข้า for loop เพือกระจาย status ของ awards foreach ($result as $prop => $val) { $emp_id = $val->getID_Employee(); $con->exec("insert into award_status (ID_Employee, ID_Award) values('".$emp_id."',".$awardModel['ID_Award'].")"); } return array("status" => true); } else { $message = "มีบางอย่างผิดพลาด , กรุณาตรวจสอบข้อมูล "; return array("status" => false, "message" => $message); } } public static function update_award($awardUpdateModel) { $ID_Award = $awardUpdateModel['ID_Award']; $query = "UPDATE " . self::TABLE . " SET "; foreach ($awardUpdateModel as $prop => $val) { if($val != '') { $query .= " $prop='$val',"; } } $query = substr($query, 0, -1); $query .= " WHERE ID_Award = '" . $ID_Award . "'"; $con = Db::getInstance(); if ($con->exec($query)) { return array("status" => true); } else { return array("status" => false); } } public static function update_award_status($ID_Employee, $ID_Award) { //$ID_Message = $params['ID_Message']; $query = "UPDATE award_status SET status = 1 "; //$query = substr($query, 0, -1); $query .= " WHERE ID_Award = ".$ID_Award." and ID_Employee = '".$ID_Employee."'"; $con = Db::getInstance(); if ($con->exec($query)) { return array("status" => true); } else { return array("status" => false); } } public static function delete_award($ID_Award) { $query = "DELETE FROM " . self::TABLE . " WHERE ID_Award = '{$ID_Award}' "; $con = Db::getInstance(); if ($con->exec($query)) { return array("status" => true); } else { return array("status" => false); } } }<file_sep><?php $title = "S Super Cable"; try { if (!isset($_SESSION['employee']) || !is_a($_SESSION['employee'], "Employee")) { header("Location: " . Router::getSourcePath() . "index.php"); } ob_start(); ?> <!-- Navbar --> <nav class="main-header navbar navbar-expand navbar-white navbar-light"> <!-- Left navbar links --> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" data-widget="pushmenu" href="#" role="button"><i class="fas fa-bars"></i></a> </li> </ul> <!-- Right navbar links --> <ul class="navbar-nav ml-auto"> </ul> </nav> <!-- /.navbar --> <div class=" content-wrapper"> <!-- Content Header (Page header) --> <div class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-md-12"> <h1 class="m-0">จัดการไฟล์เอกสาร</h1> <!-- content --> <div class="card"> <div class="form-group row mt-2 mb-2 mr-1"> <div class="col-md-12 text-right"> <a href="#" onclick="fileManageShow('create')" class="collapse-link text-right mt-2 mb-2 mr-2" style="color: #415468;"> <span class="btn btn-round btn-success" style=" font-size: 13px; padding: 0 15px; margin-bottom: inherit;"><i class="fa fa-plus"></i> สร้างไฟล์เอกสาร </span> </a> </div> </div> <div class="card-body p-0 d-flex"> <div class="table-responsive"> <table id="tbl_file" class="table table-md" style="width:100%;"> <thead> <tr> <th>เลขที่</th> <th>ชื่อไฟล์</th> <th>รายละเอียดไฟล์</th> <th>วันที่อัปโหลดไฟล์</th> <th>การกระทำ </th> </tr> </thead> <tbody> <?php $i=1; foreach ($file as $key => $value) { ?> <tr> <td><?php echo $i++; ?></td> <td><?php echo $value->getName_File() ; ?></td> <td><?php echo $value->getDetail_File() ; ?></td> <td><?php $date = date_create($value->getDate_Upload_File()) ; echo date_format($date, 'd/m/Y'); ?></td> <td class=" last"> <a href="#" onclick="fileManageShow('edit','<?php echo $value->getID_File(); ?>')"> <button type="button" class="btn btn-round btn-warning text-center" style=" font-size: 13px; padding: 0 15px; margin-bottom: inherit;width:96px !important;"> <i class="fa fa-wrench"></i> เเก้ไข </button> </a> <a href="#" onclick="onAction_deleteFile('<?php echo $value->getID_File(); ?>')"> <button type="button" class="btn btn-round btn-danger" style=" font-size: 13px; padding: 0 15px; margin-bottom: inherit;width:96px !important;"> <i class="fa fa-trash"></i> ลบ </button> </a> </td> </tr> <?php } ?> </tbody> </table> </div> </div> <!-- /.card-body --> </div> <!-- /.card --> <!-- eof --> </div><!-- /.col --> </div><!-- /.row --> </div><!-- /.container-fluid --> </div> <!-- /.content-header --> </div> <!-- /.content-wrapper --> <!-- Main Sidebar Container --> <aside class="main-sidebar sidebar-dark-primary elevation-4"> <!-- Brand Logo --> <a class="brand-link"> <img src="AdminLTE/dist/img/AdminLTELogo.png" alt="AdminLTE Logo" class="brand-image img-circle elevation-3" style="opacity: .8"> <span class="brand-text font-weight-light">S Super Cable</span> </a> <!-- Sidebar --> <?php include("templates/admin/sidebar_menu.inc.php"); ?> <!-- /.sidebar --> </aside> <?php # modal dialog ( edit profile ) include Router::getSourcePath() . "views/modal/modal_editprofile.inc.php"; # modal dialog ( file manage ) include Router::getSourcePath() . "views/modal/modal_filemanage.inc.php"; ?> <footer class="main-footer"> <strong>Copyright &copy; 2014-2021 <a href="https://adminlte.io">AdminLTE.io</a>.</strong> All rights reserved. <div class="float-right d-none d-sm-inline-block"> <b>Version</b> 3.1.0-rc </div> </footer> </div> <?php $content = ob_get_clean(); // $user_jsonencode = json_encode($user); // echo '<PRE>'; // print_r(ob_get_clean());exit(); include Router::getSourcePath() . "templates/layout.php"; } catch (Throwable $e) { // PHP 7++ echo "การเข้าถึงถูกปฏิเสธ: ไม่ได้รับอนุญาตให้ดูหน้านี้"; exit(1); } ?> <script type="text/javascript" src="AdminLTE/assets/js/page/manage_file.js"></script><file_sep><?php class Employee { //------------- Properties private $ID_Employee; private $Name_Employee; private $Surname_Employee; private $Username_Employee; private $Password_Employee; private $Email_Employee; private $Picture_Employee; private $User_Status_Employee; public $current_password; private const TABLE = "employee"; //----------- Getters & Setters public function getID_Employee(): string { return $this->ID_Employee; } public function setID_Employee(string $ID_Employee) { $this->ID_Employee = $ID_Employee; } public function getName_Employee(): string { return $this->Name_Employee; } public function setName_Employee(string $Name_Employee) { $this->Name_Employee = $Name_Employee; } public function getSurname_Employee(): string { return $this->Surname_Employee; } public function setSurname_Employee(string $Surname_Employee) { $this->Surname_Employee = $Surname_Employee; } public function getUsername_Employee(): string { return $this->Username_Employee; } public function setUsername_Employee(string $Username_Employee) { $this->Username_Employee = $Username_Employee; } public function getPassword_Employee(): string { return $this->Password_Employee; } public function setPassword_Employee(string $Password_Employee) { $this->Password_Employee = $Password_Employee; } public function getEmail_Employee(): string { return $this->Email_Employee; } public function setEmail_Employee(string $Email_Employee) { $this->Email_Employee = $Email_Employee; } public function getPicture_Employee(): string { return $this->Picture_Employee; } public function setPicture_Employee(string $Picture_Employee) { $this->Picture_Employee = $Picture_Employee; } public function getUser_Status_Employee(): string { return $this->User_Status_Employee; } public function setUser_Status_Employee(string $User_Status_Employee) { $this->User_Status_Employee = $User_Status_Employee; } public function getCurrent_Password_Employee(): string { return $this->current_password; } public function setCurrent_Password_Employee(string $current_password) { $this->current_password = $current_<PASSWORD>; } //----------- CRUD public static function findAll(): array { $con = Db::getInstance(); $query = "SELECT * FROM " . self::TABLE; $stmt = $con->prepare($query); $stmt->setFetchMode(PDO::FETCH_CLASS, "Employee"); $stmt->execute(); $employeeList = array(); while ($prod = $stmt->fetch()) { $employeeList[$prod->getID_Employee()] = $prod; } return $employeeList; } public static function findById(string $ID_Employee): ?Employee { $con = Db::getInstance(); $query = "SELECT * FROM " . self::TABLE . " WHERE ID_Employee = '$ID_Employee'"; $stmt = $con->prepare($query); $stmt->setFetchMode(PDO::FETCH_CLASS, "Employee"); $stmt->execute(); if ($prod = $stmt->fetch()) { return $prod; } return null; } public static function findByUser(string $Username_Employee): ?Employee { $con = Db::getInstance(); $query = "SELECT * FROM " . self::TABLE . " WHERE Username_Employee = '$Username_Employee'"; $stmt = $con->prepare($query); $stmt->setFetchMode(PDO::FETCH_CLASS, "Employee"); $stmt->execute(); if ($prod = $stmt->fetch()) { return $prod; } return null; } public static function findByAccount(string $Username_Employee, string $Password_Employee): ?Employee { $con = Db::getInstance(); $query = "SELECT * , '" . $Password_Employee . "' as current_password FROM " . self::TABLE . " WHERE Username_Employee = '$Username_Employee' AND Password_Employee = sha1('$Password_Employee')"; //echo $query;exit(); $stmt = $con->prepare($query); $stmt->setFetchMode(PDO::FETCH_CLASS, "Employee"); $stmt->execute(); if ($prod = $stmt->fetch()) { return $prod; } return null; } public function findLastestIDByRole(string $User_Status_Employee) { $con = Db::getInstance(); $query = "SELECT MAX(CAST(SUBSTRING(ID_Employee, 2, 4) AS SIGNED)) as last_id FROM " . self::TABLE . " WHERE User_Status_Employee = '$User_Status_Employee' "; //echo $query;exit(); $stmt = $con->prepare($query); $stmt->setFetchMode(PDO::FETCH_CLASS, "Employee"); $stmt->execute(); if ($prod = $stmt->fetch()) { $prefix = ""; # set prefix if ($User_Status_Employee == "Admin") { $prefix = "a"; } else if ($User_Status_Employee == "Sales") { $prefix = "s"; } else { $prefix = "u"; } # ex. 0001 $strings = ""; # hardcode เช็คว่า max id หลักไร $autoincre = intval($prod->last_id) + 1; # set digit $string_length = strlen($autoincre); for ($i = 4; $i > $string_length; $i--) { $strings .= "0"; } $strings = $strings . $autoincre; return $prefix . $strings; } return null; } # เช็คผู้ใช้ซ้ำ public function check_duplicate_username($Username_Employee , $ID_Employee = null){ $con = Db::getInstance(); $query = "SELECT * FROM " . self::TABLE; $query .= " WHERE Username_Employee = '{$Username_Employee}'"; if(!empty($ID_Employee)){ $query .= " AND ID_Employee != '{$ID_Employee}'"; } $stmt = $con->prepare($query); $stmt->setFetchMode(PDO::FETCH_CLASS, "Employee"); $stmt->execute(); $employeeList = array(); if($stmt->rowCount() > 0){ return true; } return false; } # จัดการผู้ใช้ ( เพิ่มผู้ใช้ ) public function create_user(array $params) { $con = Db::getInstance(); $values = ""; $columns = ""; foreach ($params as $prop => $val) { # case : update password if ($prop == "Password_Employee") { $new_password = $val; $val = sha1($val); } if ($prop != "Password_Employee_Confirm") { # ถ้า column แรกไม่ต้องเติมลูกน้ำ คอลัมน์อื่นเติมลูกน้ำ .. $columns = empty($columns) ? $columns .= $prop : $columns .= "," . $prop; $values .= "'$val',"; } } # เช็คผู้ใช้งานซ้ำ if(isset($params['Username_Employee'])){ $check_duplicate_user = Employee::check_duplicate_username($params['Username_Employee']); if($check_duplicate_user === true){ $message = "มีบางอย่างผิดพลาดพบผู้ใช้งานซ้ำ , กรุณาตรวจสอบข้อมูล "; return array("status" => false, "message" => $message); } } # autoincrement id employee // $ID_Employee = $this->findLastestIDByRole($params["User_Status_Employee"]); // $columns .= " ,ID_Employee "; // $values .= "'$ID_Employee',"; $values = substr($values, 0, -1); $query = "INSERT INTO " . self::TABLE . "({$columns}) VALUES ($values)"; # execute query if ($con->exec($query)) { return array("status" => true); } else { $message = "มีบางอย่างผิดพลาด , กรุณาตรวจสอบข้อมูล "; return array("status" => false, "message" => $message); } } # จัดการผู้ใช้ ( เพิ่มผู้ใช้ ) public function create_user_at_once(array $params) { //$status_header_column = true; $con = Db::getInstance(); // turn of auto commit $con->beginTransaction(); foreach ($params as $k => $v) { $values = ""; $columns = ""; foreach ($v as $prop => $val) { if ($prop == "Password_Employee") { $new_password = $val; $val = sha1($val); } if ($prop != "Password_Employee_Confirm") { # ถ้า column แรกไม่ต้องเติมลูกน้ำ คอลัมน์อื่นเติมลูกน้ำ .. $columns = empty($columns) ? $columns .= $prop : $columns .= "," . $prop; $values .= "'$val',"; } } #เช็คว่ามี ID ส่งมาไหม if (!isset($v['ID_Employee'])) { $con->rollBack(); $message = "มีบางอย่างผิดพลาด , ไอดีพนักงานไม่สามารถเป็นค่าว่างได้ "; return array("status" => false, "message" => $message); } #check duplicate $check_duplicate = Employee::findById($v['ID_Employee']); if (!empty($check_duplicate)) { # rollback when got error $con->rollBack(); $message = "มีบางอย่างผิดพลาด , มีไอดีพนักงาน {$v['ID_Employee']} ในระบบเเล้ว"; return array("status" => false, "message" => $message); } #eof check duplicate #check user name ซ้ำ $check_duplicate_user = Employee::findByUser($v['Username_Employee']); if (!empty($check_duplicate_user)) { # rollback when got error $con->rollBack(); $message = "มีบางอย่างผิดพลาด , มีผู้ใช้ {$v['Username_Employee']} ในระบบเเล้ว"; return array("status" => false, "message" => $message); } #eof #check first char contains only letters //เช็คถ้าตัวอักษรตัวแรกไม่ใช่ภาษาอังกฤษ return error กลับไปครับ $first_char = substr($v['ID_Employee'], 0, 1); if (!ctype_alpha($first_char)) { # rollback when got error $con->rollBack(); $message = "มีบางอย่างผิดพลาด , ตัวอักษรเเรกของไอดีพนักงาน(you value is {$first_char}) ต้องเป็นตัวอักษร"; return array("status" => false, "message" => $message); } # insert ลง db $values = substr($values, 0, -1); $query = "INSERT INTO " . self::TABLE . "({$columns}) VALUES ($values)"; //echo $query;exit(); # execute query if ($con->exec($query)) { # do something } else { # rollback when got error $con->rollBack(); $message = "มีบางอย่างผิดพลาด , กรุณาตรวจสอบข้อมูล "; return array("status" => false, "message" => $message); } } # commit $con->commit(); return array("status" => true); } # แก้ไข user public function edit_user(array $params, string $employee_id) { # เช็คผู้ใช้งานซ้ำ if(isset($params['Username_Employee'])){ $check_duplicate_user = Employee::check_duplicate_username($params['Username_Employee'] , $employee_id ); if($check_duplicate_user === true){ $message = "มีบางอย่างผิดพลาดพบผู้ใช้งานซ้ำ , กรุณาตรวจสอบข้อมูล "; return array("status" => false, "message" => $message); } } $query = "UPDATE " . self::TABLE . " SET "; foreach ($params as $prop => $val) { # case : update password if (!empty($val)) { if ($prop == "Password_Employee") { $new_password = $val; $val = sha1($val); } if ($prop != "Password_Employee_Confirm") { $query .= " $prop='$val',"; } } } $query = substr($query, 0, -1); $query .= " WHERE ID_Employee = '" . $employee_id . "'"; //echo $query;exit(); $con = Db::getInstance(); if ($con->exec($query)) { return array("status" => true); } else { return array("status" => false); } } # ลบ user public function delete_user($ID_Employee) { $query = "DELETE FROM " . self::TABLE . " WHERE ID_Employee = '{$ID_Employee}' "; $con = Db::getInstance(); if ($con->exec($query)) { return array("status" => true); } else { return array("status" => false); } } public function file_log(string $file_name, int $id) { $query = "UPDATE file_log SET file_name = '{$file_name}' where id = {$id} "; //echo $query;exit(); $con = Db::getInstance(); if ($con->exec($query)) { return array("status" => true); } } # แก้ไข profile public function updateProfile( array $params , array $FILES , string $employee_id ) { $newfilename = ""; $query = "UPDATE " . self::TABLE . " SET "; foreach ($params as $prop => $val) { # case : update password if ($prop == "Password_Employee") { $new_password = $val; $val = sha1($val); } if ($prop != "Password_Employee_Confirm") { $query .= " $prop='$val',"; } } # case : update picture employee if (!empty($FILES) && isset($FILES['name'])) { if (!empty($FILES['name'])) { $temp = explode(".", $FILES["name"]); $newfilename = sha1(round(microtime(true))) . '.' . end($temp); $query .= " Picuture_Employee= '{$newfilename}''"; } } $query = substr($query, 0, -1); $query .= " WHERE ID_Employee = '" . $employee_id . "'"; //echo $query;exit(); $con = Db::getInstance(); if ($con->exec($query)) { # update new pic $target_file = Router::getSourcePath() . "images/" . $newfilename; if (!empty($FILES) && isset($FILES['name'])) { if (!empty($FILES['name'])) { move_uploaded_file($FILES["tmp_name"], $target_file); } } # set new session $employee = $this->findByAccount($params['Username_Employee'], $new_password); $_SESSION['employee'] = $employee; $this->setCurrent_Password_Employee($new_password); return array("status" => true, "role" => $employee->getUser_Status_Employee()); } else { $employee = $this->findById($employee_id); $message = "มีบางอย่างผิดพลาด , กรุณาตรวจสอบข้อมูล "; return array("status" => false, "role" => $employee->getUser_Status_Employee(), "message" => $message); } } public function export_excel(string $page) { } } <file_sep><?php $title = "S Super Cable"; try { if (!isset($_SESSION['employee']) || !is_a($_SESSION['employee'], "Employee")) { header("Location: " . Router::getSourcePath() . "index.php"); } ob_start(); ?> <!-- Navbar --> <nav class="main-header navbar navbar-expand navbar-white navbar-light"> <!-- Left navbar links --> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" data-widget="pushmenu" href="#" role="button"><i class="fas fa-bars"></i></a> </li> </ul> <!-- Right navbar links --> <ul class="navbar-nav ml-auto"> </ul> </nav> <!-- /.navbar --> <div class=" content-wrapper"> <!-- Content Header (Page header) --> <div class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-md-12"> <h1 class="m-0">ข่าวสาร</h1><?php echo "ข้อความที่ไม่ได้อ่าน <font color=red>".$countAll[0]."</font>"; ?> <div class="card"> <div class="card-body p-0 d-flex"> <div class="table-responsive"> <table id="example2" class="table table-md" style="width:100%;"> <thead> <tr> <th>รูปภาพ</th> <th>หัวข่าวสาร</th> <th>เนื้อข่าวสาร</th> <th>วันเวลา</th> <th>การกระทำ </th> </tr> </thead> <tbody> <?php $i = 1; foreach ($message as $key => $value) { ?> <tr> <td><img src=<?php echo $value->getPicture_Message(); ?> width=350 height=350></td> <td><?php echo $value->getTittle_Message() ; ?></td> <td><?php echo $value->getText_Message(); ?></td> <td><?php echo $value->getDate_Message(); ?></td> <td class=" last"> <?php if ($value->getStatus() == 0) { ?> <button type="button" onclick="location.replace('index.php?controller=News&action=update_status_news&ID_Message=<?=$value->getID_Message()?>');" class="btn btn-round btn-warning text-center" style=" font-size: 13px; padding: 0 15px; margin-bottom: inherit;width:96px !important;"> อ่าน </button> <?php } else { ?> <button type="button" class="btn btn-round btn-danger" style=" font-size: 13px; padding: 0 15px; margin-bottom: inherit;width:96px !important;"> อ่านแล้ว </button> <?php } ?> </td> </tr> <?php } ?> </tbody> </table> </div> </div> <!-- /.card-body --> </div> </div><!-- /.col --> </div><!-- /.row --> </div><!-- /.container-fluid --> </div> <!-- /.content-header --> <!-- Content Header (Page header) --> <!-- /.content-header --> </div><!-- /.row --> </div><!-- /.container-fluid --> </div> </div> <!-- Main Sidebar Container --> <aside class="main-sidebar sidebar-dark-primary elevation-4"> <!-- Brand Logo --> <a class="brand-link"> <img src="AdminLTE/dist/img/AdminLTELogo.png" alt="AdminLTE Logo" class="brand-image img-circle elevation-3" style="opacity: .8"> <span class="brand-text font-weight-light">S Super Cable</span> </a> <!-- Sidebar --> <?php include("templates/users/sidebar_menu.inc.php"); ?> <!-- /.sidebar --> </aside> <?php # modal dialog ( edit profile ) include Router::getSourcePath() . "views/modal/modal_editprofile.inc.php"; ?> <footer class="main-footer"> <strong>Copyright &copy; 2014-2021 <a href="https://adminlte.io">AdminLTE.io</a>.</strong> All rights reserved. <div class="float-right d-none d-sm-inline-block"> <b>Version</b> 3.1.0-rc </div> </footer> <?php $content = ob_get_clean(); include Router::getSourcePath() . "templates/layout.php"; } catch (Throwable $e) { // PHP 7++ echo "การเข้าถึงถูกปฏิเสธ: ไม่ได้รับอนุญาตให้ดูหน้านี้"; exit(1); } ?> <script> $(function () { $("#example1").DataTable({ lengthMenu: [1,5, 10, 20, 50, 100], "responsive": true, "lengthChange": false, "autoWidth": false, "buttons": ["copy", "csv", "excel", "pdf", "print", "colvis"] }).buttons().container().appendTo('#example1_wrapper .col-md-6:eq(0)'); $('#example2').DataTable({ lengthMenu: [1,5, 10, 20, 50, 100], "paging": true, "lengthChange": true, "searching": true, "ordering": true, "info": true, "autoWidth": false, "responsive": true, "language": { "sLengthMenu": "แสดง _MENU_ เร็คคอร์ด ต่อหน้า", "sZeroRecords": "ไม่เจอข้อมูลที่ค้นหา", "sInfo": "แสดง _START_ ถึง _END_ ของ _TOTAL_ เร็คคอร์ด", "sInfoEmpty": "แสดง 0 ถึง 0 ของ 0 เร็คคอร์ด", "sInfoFiltered": "(จากเร็คคอร์ดทั้งหมด _MAX_ เร็คคอร์ด)", "sSearch": "ค้นหา :", "aaSorting": [[0, 'desc']], "paginate": { "sFirst": "หน้าแรก", "sPrevious": "ก่อนหน้า", "sNext": "ถัดไป", "sLast": "หน้าสุดท้าย" } }, }); $('#example3').DataTable({ "paging": true, "lengthChange": true, "searching": true, "ordering": true, "info": true, "autoWidth": false, "responsive": true, "language": { "sLengthMenu": "แสดง _MENU_ เร็คคอร์ด ต่อหน้า", "sZeroRecords": "ไม่เจอข้อมูลที่ค้นหา", "sInfo": "แสดง _START_ ถึง _END_ ของ _TOTAL_ เร็คคอร์ด", "sInfoEmpty": "แสดง 0 ถึง 0 ของ 0 เร็คคอร์ด", "sInfoFiltered": "(จากเร็คคอร์ดทั้งหมด _MAX_ เร็คคอร์ด)", "sSearch": "ค้นหา :", "aaSorting": [[0, 'desc']], "paginate": { "sFirst": "หน้าแรก", "sPrevious": "ก่อนหน้า", "sNext": "ถัดไป", "sLast": "หน้าสุดท้าย", "oAria": { "sSortAscending": ": เปิดใช้งานการเรียงข้อมูลจากน้อยไปมาก", "sSortDescending": ": เปิดใช้งานการเรียงข้อมูลจากมากไปน้อย" } } }, }); }); </script> <script type="text/javascript" src="AdminLTE/assets/js/page/manage_news.js"></script> <!-- --> <file_sep><?php try { $title = "S Super Cable"; if (!isset($_SESSION['employee']) || !is_a($_SESSION['employee'], "Employee")) { header("Location: " . Router::getSourcePath() . "index.php"); } ob_start(); ?> <!-- Navbar --> <nav class="main-header navbar navbar-expand navbar-white navbar-light"> <!-- Left navbar links --> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" data-widget="pushmenu" href="#" role="button"><i class="fas fa-bars"></i></a> </li> </ul> <!-- Right navbar links --> <ul class="navbar-nav ml-auto"> </ul> </nav> <!-- /.navbar --> <div class=" content-wrapper"> <!-- Content Header (Page header) --> <div class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-md-12"> <h1 class="m-0">จัดการบริษัทลูกค้า</h1> <!-- content --> <div class="card"> <!-- <div class="card-header"> <h3 class="card-title">User Management</h3> </div> --> <!-- /.card-header --> <div class="form-group row mt-2 mb-2 mr-1"> <div class="col-md-12 text-right"> <!-- <a href="index.php?controller=Company&action=export_pdf"--> <!-- class="collapse-link text-right mt-2 mb-2 mr-2" style="color: #415468;">--> <!-- <span class="btn btn-round btn-success"--> <!-- style=" font-size: 13px; padding: 0 15px; margin-bottom: inherit;"><i--> <!-- class="fa fa-file"></i> ดาวน์โหลดไฟล์ </span>--> <!-- </a>--> <a href="#" onclick="importShow()" class="collapse-link text-right mt-2 mb-2 mr-2" style="color: #415468;"> <span class="btn btn-round btn-success" style=" font-size: 13px; padding: 0 15px; margin-bottom: inherit;"><i class="fa fa-file"></i> อัปโหลดไฟล์ excel </span> </a> <a href="#" onclick="companymanageShow('create')" class="collapse-link text-right mt-2 mb-2 mr-2" style="color: #415468;"> <span class="btn btn-round btn-success" style=" font-size: 13px; padding: 0 15px; margin-bottom: inherit;"><i class="fa fa-plus"></i> สร้างบริษัทลูกค้า </span> </a> </div> </div> <div class="card-body p-0 d-flex"> <div class="table-responsive"> <table id="tbl_companymanagement" class="table table-md" stlye="width:100%;"> <thead> <tr> <th>เลขที่</th> <th>ชื่อบริษัท</th> <!--<th>ที่อยู่บริษัท</th>--> <th>เบอร์บริษัท</th> <!-- <th>อีเมล์บริษัท</th> <th>เลขผู้เสียภาษี</th> --> <th>วงเงินสูงสุด</th> <!-- <th>Credit Term</th> <th>Cluster</th> <th>ชื่อที่ติดต่อ</th> <th>ติด Blacklist</th> <th>สาเหตุที่ติด</th> --> <th>อำเภอ/จังหวัด</th> <th>การกระทำ</th> </tr> </thead> <tbody> <?php $i = 1; ?> <?php foreach ($company as $key => $value) { ?> <tr> <td><?php echo $i++; ?></td> <td><?php echo $value->getName_Company(); ?></td> <td><?php echo $value->getTel_Company(); ?></td> <td><?php echo number_format($value->getCredit_Limit_Company(), 2); ?></td> <td><?php echo $value->getAMPHUR_NAME(). "/" .$value->getPROVINCE_NAME(); ?></td> <td class=" last text-center"> <a href="#" onclick="companymanageShow('view','<?php echo $value->getID_Company(); ?>')"> <button type="button" class="btn btn-round btn-info" style=" font-size: 13px; padding: 0 15px; margin-bottom: inherit;width:96px !important;"> <i class="fa fa-eye"></i>เพิ่มเติม </button> </a> <a href="#" onclick="companymanageShow('edit','<?php echo $value->getID_Company(); ?>')"> <button type="button" class="btn btn-round btn-warning" style=" font-size: 13px; padding: 0 15px; margin-bottom: inherit;width:96px !important;"> <i class="fa fa-wrench"></i> เเก้ไข </button> </a> <a href="#" onclick="onaction_deletecompany('<?php echo $value->getID_Company(); ?>')"> <button type="button" class="btn btn-round btn-danger" style=" font-size: 13px; padding: 0 10px; margin-bottom: inherit;width:96px !important;"> <i class="fa fa-trash"></i> ลบ </button> </a> </td> </tr> <?php } ?> </tbody> </table> </div> </div> <!-- /.card-body --> </div> <!-- /.card --> <!-- eof --> </div><!-- /.col --> </div><!-- /.row --> </div><!-- /.container-fluid --> </div> <!-- /.content-header --> </div> <!-- /.content-wrapper --> <!-- Main Sidebar Container --> <aside class="main-sidebar sidebar-dark-primary elevation-4"> <!-- Brand Logo --> <a class="brand-link"> <img src="AdminLTE/dist/img/AdminLTELogo.png" alt="AdminLTE Logo" class="brand-image img-circle elevation-3" style="opacity: .8"> <span class="brand-text font-weight-light">S Super Cable</span> </a> <!-- Sidebar --> <?php include("templates/admin/sidebar_menu.inc.php"); ?> <!-- /.sidebar --> </aside> <?php # modal dialog ( edit profile ) include Router::getSourcePath() . "views/modal/modal_editprofile.inc.php"; # modal dialog ( company manage ) include Router::getSourcePath() . "views/modal/modal_companymanage.inc.php"; # modal dialog ( import excel company ) include Router::getSourcePath() . "views/modal/modal_importcompany.inc.php"; ?> <footer class="main-footer"> <strong>Copyright &copy; 2014-2021 <a href="https://adminlte.io">AdminLTE.io</a>.</strong> All rights reserved. <div class="float-right d-none d-sm-inline-block"> <b>Version</b> 3.1.0-rc </div> </footer> </div> <?php $content = ob_get_clean(); // $user_jsonencode = json_encode($user); // echo '<PRE>'; // print_r(ob_get_clean());exit(); include Router::getSourcePath() . "templates/layout.php"; } catch (Throwable $e) { // PHP 7++ echo "การเข้าถึงถูกปฏิเสธ: ไม่ได้รับอนุญาตให้ดูหน้านี้"; exit(1); } ?> <script type="text/javascript" src="AdminLTE/assets/js/page/manage_company.js"></script> <file_sep><?php class FileController { /** * handleRequest จะทำการตรวจสอบ action และพารามิเตอร์ที่ส่งเข้ามาจาก Router * แล้วทำการเรียกใช้เมธอดที่เหมาะสมเพื่อประมวลผลแล้วส่งผลลัพธ์กลับ * * @param string $action ชื่อ action ที่ผู้ใช้ต้องการทำ * @param array $params พารามิเตอร์ที่ใช้เพื่อในการทำ action หนึ่งๆ */ public function handleRequest(string $action = "index", array $params) { switch ($action) { case "index": $this->index(); break; case "manage_file" : $this->$action(); break; case "create_file": $FILE = isset($params["FILES"]["Path_File"]) ? $params["FILES"]["Path_File"] : ""; $result = $this->$action($params["POST"], $FILE); echo $result; break; case "findById" : $ID_File = isset($params["POST"]["ID_File"]) ? $params["POST"]["ID_File"] : ""; if (!empty($ID_File)) { $result = $this->$action($ID_File); echo $result; } break; case "edit_file" : $FILE = isset($params["FILES"]) ? $params["FILES"] : ""; $Params= isset($params["POST"]) ? $params["POST"] : ""; $ID_File = isset($params["GET"]["ID_File"]) ? $params["GET"]["ID_File"] : ""; $result = $this->$action($params["POST"] ,$FILE, $ID_File); echo $result; break; case "delete_file": $params = isset($params["GET"]["ID_File"]) ? $params["GET"]["ID_File"] : ""; $result = $this->$action($params); // print_r($params); echo $result; break; default: break; } } private function create_file($params, $FILE) { $access_file = new File(); # สร้างไฟล์ $Name_File = $params["Name_File"] ; $Path_File = !empty($FILE) ? $FILE['name'][0] : "" ; $Detail_File = $params["Detail_File"] ; $locate = ""; if (!empty($FILE) && !empty($FILE['name'])) { $tmp_name = $FILE['tmp_name'][0]; $locate = Router::getSourcePath() . "uploads/" . $Path_File ; // copy original file to destination file move_uploaded_file($tmp_name, $locate); } $access_file_params = array( "Name_File" => $Name_File, "Path_File" => $locate, "Detail_File" => $Detail_File, ); $result = $access_file->create_file( $access_file_params ); return json_encode($result); } private function findById(string $ID_File) { $file = File::findById($ID_File);//echo json_encode($employee); // echo json_encode(array("data" => $data_sendback)); $data_sendback = array( "ID_File" => $file->getID_File(), "Name_FIle" => $file->getName_File(), "Path_File" => $file->getPath_File(), "Detail_File" => $file->getDetail_File(), "Date_Upload_File" => $file->getDate_Upload_File(), ); echo json_encode(array("data" => $data_sendback)); } private function edit_file($params, $FILE, $ID_File) { # อัปเดตไฟล์ $access_file = new File(); $Name_File = $params["Name_File"] ; $Detail_File = $params["Detail_File"] ; $Date_Upload_File = $params["Date_Upload_File"] ; $locate = ""; $Path_File = !empty($FILE) ? $FILE['name'][0] : "" ; if (!empty($FILE) && !empty($FILE['name'])) { $tmp_name = $FILE['tmp_name'][0]; $locate = Router::getSourcePath() . "uploads/" . $Path_File ; // copy original file to destination file move_uploaded_file($tmp_name, $locate); } $access_file_params = array( "ID_File" => $ID_File, "Name_File" => $Name_File, "Path_File" => $locate, "Detail_File" => $Detail_File, ); $result = $access_file->update_file( $access_file_params ); return json_encode($result); } private function delete_file($params) { $access_file = new File(); $result = $access_file->delete_file( $params ); return json_encode($result); } private function error_handle(string $message) { $this->index($message); } // ควรมีสำหรับ controller ทุกตัว private function index($message = null) { session_start(); $employee = $_SESSION["employee"]; include Router::getSourcePath() . "views/index_admin.inc.php"; } //หน้าจัดการไฟล์ private function manage_file($params = null) { session_start(); $employee = $_SESSION["employee"]; # retrieve data $employeeList = Employee::findAll(); $file = File::findAll(); include Router::getSourcePath() . "views/admin/manage_file.inc.php"; } }<file_sep><div class="modal fade" id="awardManageModal" tabindex="-1" role="dialog" aria-labelledby="awardManageModalDialog" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="awardManageTitle"></h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <!-- Form --> <form id="form_awardManage" method='post' action='' enctype="multipart/form-data"> <div class="form-group "> <label for="Tittle_Award" class="col-form-label">หัวข้อรางวัล:<span class="text-danger" >*</span></label> <input type="text" class="form-control" id="Tittle_Award" name="Tittle_Award" value="" required="required"> </div> <div class="form-group"> <label for="ID_Employee" class="col-form-label">ชื่อพนักงาน:<span class="text-danger" >*</span></label> <select class="form-control" name="ID_Employee" id="ID_Employee_Award"> <option value="" selected disabled>-กรุณาเลือกคนได้รับรางวัล-</option> <?php foreach ($employeeList as $employee) { ?> <option value="<?php echo $employee->getID_Employee(); ?>"><?php echo $employee->getName_Employee() . " " . $employee->getSurname_Employee(); ?></option> <?php } ?> </select> </div> <div class="form-group"> <!-- set default image --> <?php $pic = Router::getSourcePath() . "images/" . $employee->Picuture_Employee; ?> <!-- select image to upload --> <img id="thumnails_award_pic" browsid="award_pic" class="thumnails-premise" src="<?= $pic ?>" style=""/><span class="text-danger" >*</span> <!-- chosse file --> <input id="award_pic" name="award_pic" type="file" accept=".png, .jpg,.jpeg,.gif" style="" onchange="preview();" > </div> </form> </div> <div class="modal-footer"> <a href="#" id="button_awardManageModal" onclick="onaction_createorupdate()" data-status="" data-id="" class="btn btn-primary">ตกลง</a> <button type="button" class="btn btn-secondary" data-dismiss="modal">ยกเลิก</button> </div> </div> </div> </div> <script type="text/javascript" src="AdminLTE/assets/js/page/manage_upload_pic_award.js"></script><file_sep><div class="modal fade" id="salesmanageModal" tabindex="-1" role="dialog" aria-labelledby="salesmanageModalDialog" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="salesmanageTitle"></h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <!-- Form --> <form id="form_salesmanage" method='post' action='' enctype="multipart/form-data"> <!-- <input type="hidden" name="ID_Excel" value=""/> --> <div class="form-group" id="div_idsales"> <!-- <label for="ID_Excel" class="col-form-label">ไอดียอดขาย:</label> --> <!-- <input type="text" class="form-control" id="ID_Excel" name="ID_Excel" value=""> --> </div> <div class="form-group "> <label for="Date_Sales" class="col-form-label">วันที่ขาย:<span class="text-danger" >*</span></label> <input type="date" class="form-control" id="Date_Sales" name="Date_Sales" value="" required="required"> </div> <div class="form-group"> <label for="ID_Company" class="col-form-label">ชื่อบริษัทลูกค้า:<span class="text-danger" >*</span></label> <select class="form-control" name="ID_Company" id="ID_Company"> <?php foreach ($companyList as $company) { ?> <option value="<?php echo $company->getID_Company(); ?>"><?php echo $company->getName_Company(); ?></option> <?php } ?> </select> <!-- <input type="text" class="form-control" id="ID_Company" name="ID_Company" value="" required="required" >--> </div> <div class="form-group"> <label for="ID_Employee" class="col-form-label">ชื่อพนักงาน:<span class="text-danger" >*</span></label> <select class="form-control" name="ID_Employee" id="ID_Employee"> <?php foreach ($employeeList as $employee) { ?> <option value="<?php echo $employee->getID_Employee(); ?>"><?php echo $employee->getName_Employee() . " " . $employee->getSurname_Employee(); ?></option> <?php } ?> </select> <!-- <input type="text" class="form-control" id="ID_Employee" name="ID_Employee" value="" required="required" >--> </div> <div class="form-group"> <label for="Result_Sales" class="col-form-label">ยอดขาย:<span class="text-danger" >*</span></label> <input type="number" class="form-control" id="Result_Sales" name="Result_Sales" value="" required="required" min="0"> </div> </form> </div> <div class="modal-footer"> <a href="#" id="button_salesmanageModal" onclick="onaction_createorupdate()" data-status="" data-id="" class="btn btn-primary">ตกลง</a> <button type="button" class="btn btn-secondary" data-dismiss="modal">ยกเลิก</button> </div> </div> </div> </div><file_sep><?php class File { //------------- Properties private $ID_File; private $Name_File; private $Path_File; private $Detail_File; private $Date_Upload_File; private const TABLE = "file"; //----------- Getters & Setters public function getID_File(): int { return $this->ID_File; } public function setID_File(int $ID_File) { $this->ID_File = $ID_File; } public function getName_File(): string { return $this->Name_File; } public function setName_File(string $Name_File) { $this->Name_File = $Name_File; } public function getPath_File(): string { return $this->Path_File; } public function setPath_File(string $Path_File) { $this->Path_File = $Path_File; } public function getDetail_File(): string { if ($this->Detail_File == null) return "-"; else return $this->Detail_File; } public function setDetail_File(string $Detail_File) { $this->Detail_File = $Detail_File; } public function getDate_Upload_File(): string { return $this->Date_Upload_File; } public function setDate_Upload_File(string $Date_Upload_File) { $this->Date_Upload_File = $Date_Upload_File; } //----------- CRUD public static function findAll(): array { $con = Db::getInstance(); $query = "SELECT * FROM " . self::TABLE; $stmt = $con->prepare($query); $stmt->setFetchMode(PDO::FETCH_CLASS, "File"); $stmt->execute(); $fileList = array(); while ($prod = $stmt->fetch()) { $fileList[$prod->getID_File()] = $prod; } return $fileList; } public static function findById(string $ID_File): ?File { $con = Db::getInstance(); $query = "SELECT * FROM " . self::TABLE . " WHERE ID_File = '$ID_File'"; $stmt = $con->prepare($query); $stmt->setFetchMode(PDO::FETCH_CLASS, "File"); $stmt->execute(); if ($prod = $stmt->fetch()) { return $prod; } return null; } # จัดการไฟล์ ( เพิ่มไฟล์ ) public function create_file(array $params) { $con = Db::getInstance(); $values = ""; $columns = ""; foreach ($params as $prop => $val) { # ถ้า column แรกไม่ต้องเติมลูกน้ำ คอลัมน์อื่นเติมลูกน้ำ $columns = empty($columns) ? $columns .= $prop : $columns .= "," . $prop; $values .= "'$val',"; } $values = substr($values, 0, -1); $query = "INSERT INTO " . self::TABLE . "({$columns}) VALUES ($values)"; # execute query if ($con->exec($query)) { return array("status" => true); } else { $message = "มีบางอย่างผิดพลาด , กรุณาตรวจสอบข้อมูล "; return array("status" => false, "message" => $message); } } # แก้ไขไฟล์ public function edit_file(array $params, string $ID_File) { $query = "UPDATE " . self::TABLE . " SET "; foreach ($params as $prop => $val) { if (!empty($val)) { $query .= " $prop='$val',"; } } $query = substr($query, 0, -1); $query .= " WHERE ID_File = '" . $ID_File . "'"; //echo $query;exit(); $con = Db::getInstance(); if ($con->exec($query)) { return array("status" => true); } else { return array("status" => false); } } # ลบไฟล์ public function delete_file($ID_File) { $query = "DELETE FROM " . self::TABLE . " WHERE ID_File = '{$ID_File}' "; $con = Db::getInstance(); if ($con->exec($query)) { return array("status" => true); } else { return array("status" => false); } } } ?><file_sep><?php class Amphur { //------------- Properties private $AMPHUR_ID; private $AMPHUR_CODE; private $AMPHUR_NAME; private $PROVINCE_ID; private const TABLE = "amphur"; //----------- Getters & Setters public function getAMPHUR_ID() : int { return $this->AMPHUR_ID; } public function setAMPHUR_ID(int $AMPHUR_ID) { $this->AMPHUR_ID = $AMPHUR_ID; } public function getAMPHUR_CODE() : string { return $this->AMPHUR_CODE; } public function setAMPHUR_CODE(string $AMPHUR_CODE) { $this->AMPHUR_CODE = $AMPHUR_CODE; } public function getAMPHUR_NAME() : string { return $this->AMPHUR_NAME; } public function setAMPHUR_NAME(string $AMPHUR_NAME) { $this->AMPHUR_NAME = $AMPHUR_NAME; } public function getPROVINCE_ID() : int { return $this->PROVINCE_ID; } public function setPROVINCE_ID(int $PROVINCE_ID) { $this->PROVINCE_ID = $PROVINCE_ID; } //----------- CRUD public static function findAll(): array { $con = Db::getInstance(); $query = "SELECT * FROM " . self::TABLE; $stmt = $con->prepare($query); $stmt->setFetchMode(PDO::FETCH_CLASS, "Amphur"); $stmt->execute(); $amphurList = array(); while ($prod = $stmt->fetch()) { $amphurList[$prod->getAMPHUR_ID()] = $prod; } return $amphurList; } public static function findById(int $AMPHUR_ID): ?Amphur { $con = Db::getInstance(); $query = "SELECT * FROM " . self::TABLE . " WHERE AMPHUR_ID = '$AMPHUR_ID'"; $stmt = $con->prepare($query); $stmt->setFetchMode(PDO::FETCH_CLASS, "Amphur"); $stmt->execute(); if ($prod = $stmt->fetch()) { return $prod; } return null; } } <file_sep><div class="modal fade" id="newsManageModal" tabindex="-1" role="dialog" aria-labelledby="newsManageModalDialog" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="newsManageTitle"></h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <!-- Form --> <form id="form_newsManage" method='post' action='' enctype="multipart/form-data"> <!-- Title_Message --> <div class="form-group "> <label for="Tittle_Message" class="col-form-label">ชื่อหัวข้อข่าวสาร:<span class="text-danger" >*</span></label> <input type="text" class="form-control" id="Tittle_Message" name="Tittle_Message" value="" required="required" > </div> <!-- Text_Message --> <div class="form-group "> <label for="Text_Message" class="col-form-label">เนื้อข่าวสาร:<span class="text-danger" >*</span></label> <input type="text" class="form-control" id="Text_Message" name="Text_Message" value=""> </div> <div class="form-group"> <!-- set default image --> <?php $pic = Router::getSourcePath() . "images/" . $employee->Picuture_Employee; ?> <!-- select image to upload --> <img id="thumnails_new_profile" browsid="profile_news" class="thumnails-premise" src="<?= $pic ?>" style=""/><span class="text-danger" >*</span> <!-- chosse file --> <input id="profile_news" name="profile_news" type="file" accept=".png, .jpg,.jpeg,.gif" style="" onchange="preview();" > </div> </form> </div> <div class="modal-footer"> <a href="#" id="button_newsManageModal" onclick="onaction_createoredit()" data-status="" data-id="" class="btn btn-primary">ตกลง</a> <button type="button" class="btn btn-secondary" data-dismiss="modal">ยกเลิก</button> </div> </div> </div> </div> <script type="text/javascript" src="AdminLTE/assets/js/page/manage_upload_pic_news.js"></script><file_sep><?php class Goods { //------------- Properties private $ID_Goods; private $Name_Goods; private $Detail_Goods; private $Price_Goods; private const TABLE = "goods"; //----------- Getters & Setters public function getID_Goods(): int { return $this->ID_Goods; } public function setID_Goods(int $ID_Goods) { $this->ID_Goods = $ID_Goods; } public function getName_Goods() : string { return $this->Name_Goods; } public function setName_Goods(string $Name_Goods) { $this->Name_Goods = $Name_Goods; } public function getDetail_Goods() : string { if ($this->Detail_Goods == null) return "-"; else return $this->Detail_Goods; } public function setDetail_Goods(string $Detail_Goods) { $this->Detail_Goods = $Detail_Goods; } public function getPrice_Goods() : float { return $this->Price_Goods; } public function setPrice_Goods(float $Price_Goods) { $this->Price_Goods = $Price_Goods; } //----------- CRUD public static function findAll(): array { $con = Db::getInstance(); $query = "SELECT * FROM " . self::TABLE; $stmt = $con->prepare($query); $stmt->setFetchMode(PDO::FETCH_CLASS, "Goods"); $stmt->execute(); $goodsList = array(); while ($prod = $stmt->fetch()) { $goodsList[$prod->getID_Goods()] = $prod; } return $goodsList; } public static function findById(string $ID_Goods): ?Goods { $con = Db::getInstance(); $query = "SELECT * FROM " . self::TABLE . " WHERE ID_Goods = '$ID_Goods'"; $stmt = $con->prepare($query); $stmt->setFetchMode(PDO::FETCH_CLASS, "Goods"); $stmt->execute(); if ($prod = $stmt->fetch()) { return $prod; } return null; } # จัดการสินค้า ( เพิ่มสินค้า ) public function create_goods(array $params) { $con = Db::getInstance(); $values = ""; $columns = ""; foreach ($params as $prop => $val) { # ถ้า column แรกไม่ต้องเติมลูกน้ำ คอลัมน์อื่นเติมลูกน้ำ $columns = empty($columns) ? $columns .= $prop : $columns .= "," . $prop; $values .= "'$val',"; } $values = substr($values, 0, -1); $query = "INSERT INTO " . self::TABLE . "({$columns}) VALUES ($values)"; # execute query if ($con->exec($query)) { return array("status" => true); } else { $message = "มีบางอย่างผิดพลาด , กรุณาตรวจสอบข้อมูล "; return array("status" => false, "message" => $message); } } # จัดการสินค้า ( เพิ่มสินค้า excel ) public function create_goods_at_once(array $params) { $con = Db::getInstance(); // turn off auto commit (ปิดคำสั่งสำหรับการยืนยันการเปลี่ยนแปลงข้อมูลที่เกิดขึ้น) $con->beginTransaction(); foreach ($params as $k => $v) { $values = ""; $columns = ""; foreach ($v as $prop => $val) { # ถ้า column แรกไม่ต้องเติมลูกน้ำ คอลัมน์อื่นเติมลูกน้ำ .. $columns = empty($columns) ? $columns .= $prop : $columns .= "," . $prop; $values .= "'$val',"; } # insert ลง db $values = substr($values, 0, -1); $query = "INSERT INTO " . self::TABLE . "({$columns}) VALUES ($values)"; //echo $query;exit(); # execute query if ($con->exec($query)) { # do something } else { # rollback when got error $con->rollBack(); $message = "มีบางอย่างผิดพลาด , กรุณาตรวจสอบข้อมูล "; return array("status" => false, "message" => $message); } } # commit $con->commit(); return array("status" => true); } public function file_log(string $file_name, int $id) { $query = "UPDATE file_log SET file_name = '{$file_name}' where id = {$id} "; //echo $query;exit(); $con = Db::getInstance(); if ($con->exec($query)) { return array("status" => true); } } # แก้ไขสินค้า public function edit_goods(array $params, string $ID_Goods) { $query = "UPDATE " . self::TABLE . " SET "; foreach ($params as $prop => $val) { if (!empty($val)) { $query .= " $prop='$val',"; } } $query = substr($query, 0, -1); $query .= " WHERE ID_Goods = '" . $ID_Goods . "'"; //echo $query;exit(); $con = Db::getInstance(); if ($con->exec($query)) { return array("status" => true); } else { return array("status" => false); } } # ลบสินค้า public function delete_goods($ID_Goods) { $query = "DELETE FROM " . self::TABLE . " WHERE ID_Goods = '{$ID_Goods}' "; $con = Db::getInstance(); if ($con->exec($query)) { return array("status" => true); } else { return array("status" => false); } } public function export_excel(string $page) { } } ?><file_sep><?php // rootPath ใช้กำหนด path ของไฟล์ปัจจุบันเทียบกับ root folder ของระบบ $rootPath = "./"; require $rootPath . "classes/Router.class.php"; /** * Load Models */ spl_autoload_register(function ($class) { $path = $GLOBALS['rootPath'] . 'DAO/ActiveRecord/' . $class . '.class.php'; if (file_exists($path)) require_once $path; }); spl_autoload_register(function ($class) { $path = $GLOBALS['rootPath'] . 'DAO/' . $class . '.class.php'; if (file_exists($path)) require_once $path; }); /** * Load Controllers */ spl_autoload_register(function ($class) { $path = $GLOBALS['rootPath'] . 'controllers/' . $class . '.class.php'; if (file_exists($path)) require_once $path; }); $router = new Router($rootPath); $router->load();<file_sep><?php include('config.ini.php'); function connect() { try { $dbh = new PDO(DSN, USER, PASS); $dbh->query("SET NAMES UTF8"); return $dbh; } catch (PDOException $e) { print "Error!: " . $e->getMessage() . "<br/>"; die(); } } function select(string $sql, int $type = PDO::FETCH_ASSOC) { $conn = connect(); $result = $conn->prepare($sql); $result->execute(); if ($result->rowCount() > 0) return $result->fetchAll($type); return null; } function update(string $sql) { $conn = connect(); $stmt = $conn->prepare($sql); $stmt->execute(); } ?><file_sep># S-Super-Cable # PHP Version 7.3 only # Login : Admin Admin or User User or Sales Sales (Have 3 type) <file_sep><?php # excel library include Router::getSourcePath() . 'classes/Excel.class.php'; class CompanyController { /** * handleRequest จะทำการตรวจสอบ action และพารามิเตอร์ที่ส่งเข้ามาจาก Router * แล้วทำการเรียกใช้เมธอดที่เหมาะสมเพื่อประมวลผลแล้วส่งผลลัพธ์กลับ * * @param string $action ชื่อ action ที่ผู้ใช้ต้องการทำ * @param array $params พารามิเตอร์ที่ใช้เพื่อในการทำ action หนึ่งๆ */ public function handleRequest(string $action = "index", array $params) { switch ($action) { case "index": $this->index(); break; case "manage_company" : $this->$action(); break; case "create_company" : $result = $this->$action($params["POST"]); echo $result; break; case "edit_company" : $ID_Company = isset($params["GET"]["ID_Company"]) ? $params["GET"]["ID_Company"] : ""; $result = $this->$action($params["POST"], $ID_Company); echo $result; break; case "delete_company": $result = $this->$action($params["POST"]["ID_Company"]); echo $result; break; case "import_excel_company": $FILES = isset($params["FILES"]["file"]) ? $params["FILES"]["file"] : ""; $FILE_IMG = isset($params["FILES"]["examfile"]) ? $params["FILES"]["examfile"] : ""; $result = $this->$action($params["POST"], $FILES, $FILE_IMG); echo $result; break; case "findbyID_Company": $ID_Company = isset($params["POST"]["ID_Company"]) ? $params["POST"]["ID_Company"] : ""; //print_r($ID_Company);exit(); if (!empty($ID_Company)) { $result = $this->$action($ID_Company); echo $result; } break; case "getAmphur": $PROVINCE_ID = isset($params["POST"]["PROVINCE_ID"]) ? $params["POST"]["PROVINCE_ID"] : ""; if (!empty($PROVINCE_ID)) { $result = $this->$action($PROVINCE_ID); echo $result; } break; case "export_excel_test_company": $result = $this->$action($params["POST"]); echo $result; break; default: break; } } private function import_excel_company(array $params, array $FILES, array $FILE_IMG) { $excel = new Excel(); #UPLOAD IMAGE if (!empty($FILE_IMG) && !empty($FILE_IMG['name'])) { # update new pic $target_file_img = Router::getSourcePath() . "images/" . $FILE_IMG['name']; if (!empty($FILE_IMG) && isset($FILE_IMG['name'])) { if (!empty($FILE_IMG['name'])) { move_uploaded_file($FILE_IMG["tmp_name"], $target_file_img); $company_ = new Company(); $company_->file_log($FILE_IMG['name'], 2); } } } #UPLOAD EXCEL if (!empty($FILES) && !empty($FILES['name'])) { $path = $FILES["tmp_name"]; $object = PHPExcel_IOFactory::load($path); $params = array(); //case: การอัพโหลดไฟล์ excel ถ้าลืมใส่ column ไหนให้บอกผิด row ไหน $EXCEL_HeaderCol = array("ID_Company" => array("name" => "ไอดีบริษัท", "status" => false, "error" => "ไม่พบข้อมูลคอลัมน์ ไอดีบริษัท") , "Name_Company" => array("name" => "ชื่อบริษัท", "status" => false, "error" => "ไม่พบข้อมูลคอลัมน์ ชื่อบริษัท") , "Address_Company" => array("name" => "ที่อยู่บริษัท", "status" => false, "error" => "ไม่พบข้อมูลคอลัมน์ ที่อยู่บริษัท") , "PROVINCE_ID" => array("name" => "ไอดีจังหวัด", "status" => false, "error" => "ไม่พบข้อมูลคอลัมน์ ไอดีจังหวัด") , "AMPHUR_ID" => array("name" => "ไอดีอำเภอ", "status" => false, "error" => "ไม่พบข้อมูลคอลัมน์ ไอดีอำเภอ") , "Tel_Company" => array("name" => "เบอร์บริษัท", "status" => false, "error" => "ไม่พบข้อมูลคอลัมน์ เบอร์บริษัท") , "Email_Company" => array("name" => "อีเมล์บริษัท", "status" => false, "error" => "ไม่พบข้อมูลคอลัมน์ อีเมล์บริษัท") , "Tax_Number_Company" => array("name" => "เลขผู้เสียภาษี", "status" => false, "error" => "ไม่พบข้อมูลคอลัมน์ เลขผู้เสียภาษี") , "Credit_Limit_Company" => array("name" => "วงเงินสูงสุด", "status" => false, "error" => "ไม่พบข้อมูลคอลัมน์ วงเงินสูงสุด") , "Credit_Term_Company" => array("name" => "เครดิตเทอม", "status" => false, "error" => "ไม่พบข้อมูลคอลัมน์ เครดิตเทอม") , "Cluster_Shop" => array("name" => "คลัสเตอร์", "status" => false, "error" => "ไม่พบข้อมูลคอลัมน์ คลัสเตอร์") , "Contact_Name_Company" => array("name" => "ชื่อที่ติดต่อ", "status" => false, "error" => "ไม่พบข้อมูลคอลัมน์ ชื่อที่ติดต่อ") , "IS_Blacklist" => array("name" => "บัญชีดำ", "status" => false, "error" => "ไม่พบข้อมูลคอลัมน์ บัญชีดำ") , "Cause_Blacklist" => array("name" => "สาเหตุที่ติดบัญชีดำ", "status" => false, "error" => "ไม่พบข้อมูลคอลัมน์ สาเหตุที่ติดบัญชีดำ") ); $count = 0; foreach ($object->getWorksheetIterator() as $worksheet) { $highestRow = $worksheet->getHighestRow(); $highestColumn = $worksheet->getHighestColumn(); // echo $highestRow;exit(); // row = 2 คือ row แรก ไม่รวม header #เช็คหัวตารางชื่อตรงกันไหมใน array ที่ hardcode ไว้ if ($count != 1) { for ($col_ = 0; $col_ < 14; $col_++) { $col__cc = strval($worksheet->getCellByColumnAndRow($col_, 1)->getValue()); if ($col__cc == '') { $c = array_values($EXCEL_HeaderCol); $message = "มีบางอย่างผิดพลาด , กรุณาตรวจสอบข้อมูลไม่พบคอลัมน์ " . $c[$col_]['name']; return json_encode(array("status" => false, "message" => $message)); } else { $ccc = array_key_exists($col__cc, $EXCEL_HeaderCol); if (!$ccc) { $c = array_values($EXCEL_HeaderCol); $message = "มีบางอย่างผิดพลาด , กรุณาตรวจสอบข้อมูลไม่พบคอลัมน์ " . $c[$col_]['name']; return json_encode(array("status" => false, "message" => $message)); } } } ++$count; } #eof for ($row = 2; $row <= $highestRow; $row++) { if ($worksheet->getCellByColumnAndRow(0, $row)->getValue() != '') { $getCellArray = $this->checkemptycell_company($worksheet, $row); if ($getCellArray['status'] == false) { $c = array_values($EXCEL_HeaderCol); $message = "มีบางอย่างผิดพลาด , กรุณาตรวจสอบข้อมูลไม่พบข้อมูลในแถวที่{$row}(รวมหัวตาราง) ในคอลัมน์คือ " . $c[$getCellArray["column"]]['name'] . ''; return json_encode(array("status" => false, "message" => $message)); } $push_array = array("ID_Company" => $getCellArray["data"][0], "Name_Company" => $getCellArray["data"][1], "Address_Company" => $getCellArray["data"][2], "PROVINCE_ID" => $getCellArray["data"][3], "AMPHUR_ID" => $getCellArray["data"][4], "Tel_Company" => $getCellArray["data"][5], "Email_Company" => $getCellArray["data"][6], "Tax_Number_Company" => $getCellArray["data"][7], "Credit_Limit_Company" => $getCellArray["data"][8], "Credit_Term_Company" => $getCellArray["data"][9], "Cluster_Shop" => $getCellArray["data"][10], "Contact_Name_Company" => $getCellArray["data"][11], "IS_Blacklist" => $getCellArray["data"][12], "Cause_Blacklist" => $getCellArray["data"][13] ); array_push($params, $push_array); } else { } } } // # create user ใหม่ $company_ = new Company(); $result = $company_->create_company_at_once($params); # update new pic $target_file = Router::getSourcePath() . "uploads/" . $FILES['name']; if (!empty($FILES) && isset($FILES['name'])) { if (!empty($FILES['name'])) { move_uploaded_file($FILES["tmp_name"], $target_file); } } return json_encode($result); } # return json_encode(array("status" => true)); } private function checkemptycell_company($worksheet, $row) { $push_array = array(); for ($i = 0; $i < 14; $i++) { if (empty($worksheet->getCellByColumnAndRow($i, $row)->getValue())) { return array("status" => false, "column" => $i, "row" => $row); } else { $push_array[$i] = $worksheet->getCellByColumnAndRow($i, $row)->getValue(); } } return array("status" => true, "data" => $push_array); } private function getAmphur($PROVINCE_ID){ $access_company = new Company(); $amphur_result = $access_company->getAmphur( $PROVINCE_ID ); echo json_encode($amphur_result); } private function create_company($params) { # สร้างบริษัทลูกค้า $access_company = new Company(); $company_result = $access_company->create_company( $params ); return json_encode($company_result); } private function edit_company($params, $ID_Company) { # อัปเดตบริษัทลูกค้า $access_company = new Company(); $company_result = $access_company->edit_company( $params, $ID_Company ); echo json_encode($company_result); } private function delete_company($ID_Company) { # ลบบริษัทลูกค้า $access_company = new Company(); $company_result = $access_company->delete_company( $ID_Company ); return json_encode($company_result); } private function findbyID_Company(string $ID_Company) { $company = Company::findById($ID_Company);//echo json_encode($employee); $data_sendback = array( "ID_Company" => $company->getID_Company(), "Name_Company" => $company->getName_Company(), "Address_Company" => $company->getAddress_Company(), "PROVINCE_ID" => $company->getPROVINCE_ID(), "AMPHUR_ID" => $company->getAMPHUR_ID(), "Tel_Company" => $company->getTel_Company(), "Email_Company" => $company->getEmail_Company(), "Tax_Number_Company" => $company->getTax_Number_Company(), "Credit_Limit_Company" => $company->getCredit_Limit_Company(), "Credit_Term_Company" => $company->getCredit_Term_Company(), "Cluster_Shop" => $company->getCluster_Shop(), "Contact_Name_Company" => $company->getContact_Name_Company(), "IS_Blacklist" => $company->getIS_Blacklist(), "Cause_Blacklist" => $company->getCause_Blacklist(), ); echo json_encode(array("data" => $data_sendback)); } private function error_handle(string $message) { $this->index($message); } // ควรมีสำหรับ controller ทุกตัว private function index($message = null) { session_start(); $employee = $_SESSION["employee"]; include Router::getSourcePath() . "views/index_admin.inc.php"; } //หน้าจัดการบริษัทลูกค้า private function manage_company($params = null) { session_start(); $employee = $_SESSION["employee"]; # retrieve data $company = Company::findAll(); $file_log = Filelog::findByPage('manage_company'); $provinceList = Province::findAll(); $amphurList = Amphur::findAll(); include Router::getSourcePath() . "views/admin/manage_company.inc.php"; } //หน้า export ไฟล์ตัวอย่าง excel บริษัทลูกค้า private function export_excel_test_company($params = null) { $exportExcel = new Company(); $exportExcelCompany = Company::findAll(); try { // ob_end_clean(); // เรียนกใช้ PHPExcel $objPHPExcel = new PHPExcel(); // กำหนดค่าต่างๆ ของเอกสาร excel $objPHPExcel->getProperties()->setCreator("bp.com") ->setLastModifiedBy("bp.com") ->setTitle("PHPExcel Test Document") ->setSubject("PHPExcel Test Document") ->setDescription("Test document for PHPExcel, generated using PHP classes.") ->setKeywords("office PHPExcel php") ->setCategory("Test result file"); // กำหนดชื่อให้กับ worksheet ที่ใช้งาน $objPHPExcel->getActiveSheet()->setTitle('Report'); // กำหนด worksheet ที่ต้องการให้เปิดมาแล้วแสดง ค่าจะเริ่มจาก 0 , 1 , 2 , ...... $objPHPExcel->setActiveSheetIndex(0); // การจัดรูปแบบของ cell $objPHPExcel->getDefaultStyle() ->getAlignment() ->setVertical(PHPExcel_Style_Alignment::VERTICAL_TOP) ->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); //HORIZONTAL_CENTER //VERTICAL_CENTER // จัดความกว้างของคอลัมน์ $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20); $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20); $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20); $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20); $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20); $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20); $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20); $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20); $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(20); $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(20); $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(20); $objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(20); $objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(20); $objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(20); // กำหนดหัวข้อให้กับแถวแรก $objPHPExcel->setActiveSheetIndex(0) ->setCellValue('A1', 'ID_Company') ->setCellValue('B1', 'Name_Company') ->setCellValue('C1', 'Address_Company') ->setCellValue('D1', 'PROVINCE_ID') ->setCellValue('E1', 'AMPHUR_ID') ->setCellValue('F1', 'Tel_Company') ->setCellValue('G1', 'Email_Company') ->setCellValue('H1', 'Tax_Number_Company') ->setCellValue('I1', 'Credit_Limit_Company') ->setCellValue('J1', 'Credit_Term_Company') ->setCellValue('K1', 'Cluster_Shop') ->setCellValue('L1', 'Contact_Name_Company') ->setCellValue('M1', 'IS_Blacklist') ->setCellValue('N1', 'Cause_Blacklist');; $start_row = 2; $objPHPExcel->setActiveSheetIndex(0) ->setCellValue('A' . $start_row, "111") ->setCellValue('B' . $start_row, "FIRSTSTEP") ->setCellValue('C' . $start_row, "300/15 montisuriyawong") ->setCellValue('D' . $start_row, "1") ->setCellValue('E' . $start_row, " ") ->setCellValue('F' . $start_row, "1234567890") ->setCellValue('G' . $start_row, "<EMAIL>") ->setCellValue('H' . $start_row, "1234567891234") ->setCellValue('I' . $start_row, "50000 บาท") ->setCellValue('J' . $start_row, "30 วัน") ->setCellValue('K' . $start_row, "ภาคเอกชน") ->setCellValue('L' . $start_row, " ") ->setCellValue('M' . $start_row, "ใช่") ->setCellValue('N' . $start_row, " "); $i = 0; $filename = 'Company-' . date("dmYHis") . '.xlsx'; // กำหนดชือ่ไฟล์ นามสกุล xls หรือ xlsx $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); // Excel2007 (xlsx) หรือ Excel5 (xls) ob_clean(); $objWriter->save('./uploads/' . $filename); //download header('Content-Type: application/octet-stream'); header("Content-Transfer-Encoding: Binary"); header("Content-disposition: attachment; filename=\"" . $filename . "\""); echo file_get_contents("./uploads/" . $filename); die; return json_encode(array('status' => true, "filename" => $filename)); //ob_end_clean(); // die($objWriter); //die; } catch (Exception $e) { // status that return to frontend $status = false; // error message handle $message = $e->getMessage(); } return json_encode(array('status' => true)); } }<file_sep><?php class UserController { /** * handleRequest จะทำการตรวจสอบ action และพารามิเตอร์ที่ส่งเข้ามาจาก Router * แล้วทำการเรียกใช้เมธอดที่เหมาะสมเพื่อประมวลผลแล้วส่งผลลัพธ์กลับ * * @param string $action ชื่อ action ที่ผู้ใช้ต้องการทำ * @param array $params พารามิเตอร์ที่ใช้เพื่อในการทำ action หนึ่งๆ */ public function handleRequest(string $action = "index", array $params) { switch ($action) { case "index": $this->index(); break; default: break; } } private function error_handle(string $message) { $this->index($message); } // ควรมีสำหรับ controller ทุกตัว private function index($message = null) { session_start(); $employee = $_SESSION["employee"]; include Router::getSourcePath() . "views/index_user.inc.php"; } }<file_sep><?php class EmployeeController { /** * handleRequest จะทำการตรวจสอบ action และพารามิเตอร์ที่ส่งเข้ามาจาก Router * แล้วทำการเรียกใช้เมธอดที่เหมาะสมเพื่อประมวลผลแล้วส่งผลลัพธ์กลับ * * @param string $action ชื่อ action ที่ผู้ใช้ต้องการทำ * @param array $params พารามิเตอร์ที่ใช้เพื่อในการทำ action หนึ่งๆ */ public function handleRequest(string $action = "index", array $params) { switch ($action) { case "login": $Username_Employee = $params["POST"]["Username_Employee"] ?? ""; $Password_Employee = $params["POST"]["Password_Employee"] ?? ""; $RememberMe = $params["POST"]["RememberMe"] ?? ""; if ($Username_Employee !== "" && $Password_Employee !== "") { $this->$action($Username_Employee, $Password_Employee, $RememberMe); } else { # error handle : if empty username or password $message = json_encode("Username หรือ Password ไม่สามารถว่างได้ , โปรดลองอีกครั้ง "); header("Location: " . Router::getSourcePath() . "index.php?controller=ErrorHandle&action=error_handle&message={$message}"); } break; case "logout" : session_start(); # ลบตัวแปร session ทั้งหมด session_destroy(); # redirect ไปหน้า login // header("Location: " . Router::getSourcePath() . "index.php"); # status ที่จะ return กลับไปเป็น json echo json_encode(array("status" => true)); break; case "index": $this->index(); break; case "edit_profile": $FILES = isset($params["FILES"]["profile"]) ? $params["FILES"]["profile"] : ""; $result = $this->$action($params["POST"], $FILES); echo $result; break; case "findbyID": $ID_Employee = isset($params["POST"]["ID_Employee"]) ? $params["POST"]["ID_Employee"] : ""; if (!empty($ID_Employee)) { $result = $this->$action($ID_Employee); echo $result; } break; default: break; } } private function findbyID(string $ID_Employee) { $employee = Employee::findById($ID_Employee);//echo json_encode($employee); $data_sendback = array( "ID_Employee" => $employee->getID_Employee(), "Name_Employee" => $employee->getName_Employee(), "Surname_Employee" => $employee->getSurname_Employee(), "Username_Employee" => $employee->getUsername_Employee(), "User_Status_Employee" => $employee->getUser_Status_Employee(), "Email_Employee" => $employee->getEmail_Employee() ); echo json_encode(array("data" => $data_sendback)); } private function edit_profile(array $Params, array $FILES) { session_start(); $employee = $_SESSION["employee"]; # update profile $access_employee = new Employee(); //echo '<PRE>'; //print_r($Params);exit(); if (isset($Params["profile"])) { if (empty($Params["profile"])) { unset($Params["profile"]); } } if (isset($Params["Password_Employee_Profile"])) { $Params["Password_Employee"] = strlen($Params["Password_Employee_Profile"]) <= 0 ? $_SESSION['employee']->current_password: $Params["Password_Employee_Profile"]; unset($Params["Password_Employee_Profile"]); unset($Params["Password_Employee_Profile_Confirm"]); }else{ $Params["Password_Employee"] = $_SESSION['employee']->current_password; } $employee_update_result = $access_employee->updateProfile( $Params , $FILES , $employee->getID_Employee()); if ($employee_update_result == true) { $_POST['Username_Employee'] = $Params['Username_Employee']; $_POST['Password_Employee'] = $Params['Password_Employee']; } return json_encode($employee_update_result); } private function login(string $Username_Employee, string $Password_Employee, string $RememberMe) { $employee = Employee::findByAccount($Username_Employee, $Password_Employee); if ($employee !== null) { session_start(); $_SESSION['employee'] = $employee; # using cookie that store value on the client-side if ($RememberMe != "") { # clear old cookie before add new one if (isset($_COOKIE["remember_me_username_employee"]) || isset($_COOKIE["remember_me_password_employee"])) { unset($_COOKIE['remember_me_username_employee']); setcookie('remember_me_username_employee', null, -1, '/'); unset($_COOKIE['remember_me_password_employee']); setcookie('remember_me_password_employee', null, -1, '/'); } $cookie_value = array( 'Username_Employee' => base64_encode(base64_encode($Username_Employee)), 'Password_Employee' => base64_encode(base64_encode($<PASSWORD>)) ); setcookie("remember_me_username_employee" , $cookie_value['Username_Employee'] , time() + (86400 * 30) // 86400 = 1 day , "/"); setcookie("remember_me_password_employee" , $cookie_value['Password_Employee'] , time() + (86400 * 30) , "/"); } // print_r($employee -> getUser_Status_Employee()); if ($employee->getUser_Status_Employee() == "Admin") { include Router::getSourcePath() . "views/index_admin.inc.php"; } else if ($employee->getUser_Status_Employee() == "Sales") { include Router::getSourcePath() . "views/index_sales.inc.php"; } else if ($employee->getUser_Status_Employee() == "User") { include Router::getSourcePath() . "views/index_user.inc.php"; } } else { # error handle : if username or password incorrect $message = json_encode("Username or Password incorrect "); header("Location: " . Router::getSourcePath() . "index.php?controller=ErrorHandle&action=error_handle&message={$message}"); } } // ควรมีสำหรับ controller ทุกตัว private function index() { include Router::getSourcePath() . "views/login.inc.php"; } }<file_sep><?php $title = "S Super Cable"; try { if (!isset($_SESSION['employee']) || !is_a($_SESSION['employee'], "Employee")) { header("Location: " . Router::getSourcePath() . "index.php"); } ob_start(); ?> <div class="row"> <div class="col-lg-3 col-6"> <!-- small card --> <div class="small-box bg-info"> <div class="inner"> <?php # find all employee $user_count = count(Employee::findAll()); ?> <h3><?php echo isset($user_count) ? $user_count : ""; ?> </h3> <p>ผู้ใช้งาน</p> </div> <div class="icon"> <i class="fas fa-user"></i> </div> <a href="index.php?controller=Admin&action=manage_user" class="small-box-footer"> เพิ่มเติม <i class="fas fa-user"></i> </a> </div> </div> <div class="col-lg-3 col-6"> <!-- small card --> <div class="small-box bg-gradient-success"> <div class="inner"> <?php # find all company $company_count = count(Company::findAll()); ?> <h3><?php echo isset($company_count) ? $company_count : ""; ?> </h3> <p>บริษัท</p> </div> <div class="icon"> <i class="fas fa-store"></i> </div> <a href="index.php?controller=Company&action=manage_company" class="small-box-footer"> เพิ่มเติม <i class="fas fa-store"></i> </a> </div> </div> <div class="col-lg-3 col-6"> <!-- small card --> <div class="small-box bg-gradient-warning"> <div class="inner"> <?php # find all sales $sales_count = count(Sales::findAll()); ?> <h3><?php echo isset($sales_count) ? $sales_count : ""; ?> </h3> <p>ยอดขาย</p> </div> <div class="icon"> <i class="fas fa-wallet"></i> </div> <a href="index.php?controller=ResultSales&action=manage_sales" class="small-box-footer"> เพิ่มเติม <i class="fas fa-wallet"></i> </a> </div> </div> <div class="col-lg-3 col-6"> <!-- small card --> <div class="small-box bg-gradient-danger "> <div class="inner"> <?php # find all news $news_count = count(Message::fetchAll()); ?> <h3><?php echo isset($news_count) ? $news_count : ""; ?> </h3> <p>ข่าวสาร</p> </div> <div class="icon"> <i class="fas fa-comments"></i> </div> <a href="index.php?controller=News&action=manage_news" class="small-box-footer"> เพิ่มเติม <i class="fas fa-comments"></i> </a> </div> </div> <div class="col-lg-3 col-6"> <!-- small card --> <div class="small-box bg-gradient-light "> <div class="inner"> <?php # find all award $award_count = count(Award::fetchAll()); ?> <h3><?php echo isset($award_count) ? $award_count : ""; ?> </h3> <p>รางวัล</p> </div> <div class="icon"> <i class="fas fa-award"></i> </div> <a href="index.php?controller=Award&action=manage_award" class="small-box-footer"> เพิ่มเติม <i class="fas fa-award"></i> </a> </div> </div> <div class=""> <!-- small card --> <div class="small-box bg-gradient-blue "> <div class="inner"> <?php # find all promotion $promotion_count = count(Promotion::findAll()); ?> <h3><?php echo isset($promotion_count) ? $promotion_count : ""; ?> </h3> <p>สินค้าส่งเสริมการขาย</p> </div> <div class="icon"> <i class="fas fa-gifts"></i> </div> <a href="index.php?controller=Promotion&action=manage_promotion" class="small-box-footer"> เพิ่มเติม <i class="fas fa-gifts"></i> </a> </div> </div> <div class="col-lg-3 col-6"> <!-- small card --> <div class="small-box bg-gradient-gray "> <div class="inner"> <?php # find all goods $goods_count = count(Goods::findAll()); ?> <h3><?php echo isset($goods_count) ? $goods_count : ""; ?> </h3> <p>สินค้า</p> </div> <div class="icon"> <i class="fas fa-boxes"></i> </div> <a href="index.php?controller=Goods&action=manage_goods" class="small-box-footer"> เพิ่มเติม <i class="fas fa-boxes"></i> </a> </div> </div> </div> <?php $content = ob_get_clean(); // $user_jsonencode = json_encode($user); // echo '<PRE>'; // print_r(ob_get_clean());exit(); include Router::getSourcePath() . "templates/layout.php"; } catch (Throwable $e) { // PHP 7++ echo "การเข้าถึงถูกปฏิเสธ: ไม่ได้รับอนุญาตให้ดูหน้านี้"; exit(1); } ?><file_sep><?php class IndexController { public function handleRequest(string $action = "index", array $params = null) { $this->$action(); } private function getRememberMe() { $arReturn = array( 'Username_Employee' => '', 'Password_Employee' => '' ); if (isset($_COOKIE["remember_me_username_employee"]) && isset($_COOKIE["remember_me_password_employee"])) { $username = base64_decode(base64_decode($_COOKIE["remember_me_username_employee"])); $password = base64_decode(base64_decode($_COOKIE["remember_me_password_employee"])); $arReturn['Username_Employee'] = $username; $arReturn['Password_Employee'] = $password; } return $arReturn; } private function index() { $remember_me = $this->getRememberMe(); include Router::getSourcePath() . "views/login.inc.php"; } }<file_sep><?php class ErrorHandleController { /** * handleRequest จะทำการตรวจสอบ action และพารามิเตอร์ที่ส่งเข้ามาจาก Router * แล้วทำการเรียกใช้เมธอดที่เหมาะสมเพื่อประมวลผลแล้วส่งผลลัพธ์กลับ * * @param string $action ชื่อ action ที่ผู้ใช้ต้องการทำ * @param array $params พารามิเตอร์ที่ใช้เพื่อในการทำ action หนึ่งๆ */ public function handleRequest(string $action = "index", array $params) { switch ($action) { case "error_handle": $message = $params["GET"]["message"] ?? ""; $this->$action($message); break; default: break; } } private function error_handle(string $message) { $this->index($message); } // ควรมีสำหรับ controller ทุกตัว private function index($message) { include Router::getSourcePath() . "views/error_handle.inc.php"; } }<file_sep><?php class Company { //------------- Properties private $ID_Company; private $Name_Company; private $Address_Company; private $Tel_Company; private $Email_Company; private $Tax_Number_Company; private $Credit_Limit_Company; private $Credit_Term_Company; private $Cluster_Shop; private $Contact_Name_Company; private $IS_Blacklist; private $Cause_Blacklist; private $AMPHUR_ID; private $AMPHUR_CODE; private $AMPHUR_NAME; private $PROVINCE_ID; private $PROVINCE_NAME; private const TABLE = "company"; //----------- Getters & Setters public function getID_Company(): int { return $this->ID_Company; } public function setID_Company(int $ID_Company) { $this->ID_Company = $ID_Company; } public function getName_Company(): string { return $this->Name_Company; } public function setName_Company(string $Name_Company) { $this->Name_Company = $Name_Company; } public function getAddress_Company(): string { return $this->Address_Company; } public function setAddress_Company(string $Address_Company) { $this->Address_Company = $Address_Company; } public function getTel_Company(): string { return $this->Tel_Company; } public function setTel_Company(string $Tel_Company) { $this->Tel_Company = $Tel_Company; } public function getEmail_Company(): string { return $this->Email_Company; } public function setEmail_Company(string $Email_Company) { $this->Email_Company = $Email_Company; } public function getTax_Number_Company(): string { return $this->Tax_Number_Company; } public function setTax_Number_Company(string $Tax_Number_Company) { $this->Tax_Number_Company = $Tax_Number_Company; } public function getCredit_Limit_Company(): int { return $this->Credit_Limit_Company; } public function setCredit_Limit_Company(int $Credit_Limit_Company) { $this->Credit_Limit_Company = $Credit_Limit_Company; } public function getCredit_Term_Company(): string { return $this->Credit_Term_Company; } public function setCredit_Term_Company(string $Credit_Term_Company) { $this->Credit_Term_Company = $Credit_Term_Company; } public function getCluster_Shop(): string { return $this->Cluster_Shop; } public function setCluster_Shop(string $Cluster_Shop) { $this->Cluster_Shop = $Cluster_Shop; } public function getContact_Name_Company(): string { if ($this->Contact_Name_Company == null) return "-"; else return $this->Contact_Name_Company; } public function setContact_Name_Company(string $Contact_Name_Company) { $this->Contact_Name_Company = $Contact_Name_Company; } public function getIS_Blacklist(): string { return $this->IS_Blacklist; } public function setIS_Blacklist(string $IS_Blacklist) { $this->IS_Blacklist = $IS_Blacklist; } public function getCause_Blacklist(): string { if ($this->Cause_Blacklist == null) return "-"; else return $this->Cause_Blacklist; } public function setCause_Blacklist(string $Cause_Blacklist) { $this->Cause_Blacklist = $Cause_Blacklist; } public function getAMPHUR_ID(): string { if ($this->AMPHUR_ID == null) return "-"; else return $this->AMPHUR_ID; } public function setAMPHUR_ID(string $AMPHUR_ID) { $this->AMPHUR_ID = $AMPHUR_ID; } public function getAMPHUR_CODE(): string { if ($this->AMPHUR_CODE == null) return "-"; else return $this->AMPHUR_CODE; } public function setAMPHUR_CODE(string $AMPHUR_CODE) { $this->AMPHUR_CODE = $AMPHUR_CODE; } public function getAMPHUR_NAME(): string { if ($this->AMPHUR_NAME == null) return "-"; else return $this->AMPHUR_NAME; } public function setAMPHUR_NAME(string $AMPHUR_NAME) { $this->AMPHUR_NAME = $AMPHUR_NAME; } public function getPROVINCE_ID(): string { if ($this->PROVINCE_ID == null) return "-"; else return $this->PROVINCE_ID; } public function setPROVINCE_ID(string $PROVINCE_ID) { $this->PROVINCE_ID = $PROVINCE_ID; } public function getPROVINCE_NAME(): string { if ($this->PROVINCE_NAME == null) return "-"; else return $this->PROVINCE_NAME; } public function setPROVINCE_NAME(string $PROVINCE_NAME) { $this->PROVINCE_NAME = $PROVINCE_NAME; } //----------- CRUD public static function findAll(): array { $con = Db::getInstance(); //$query = "SELECT * FROM " . self::TABLE; $query = "SELECT " . self::TABLE . ".*,province.PROVINCE_NAME ,amphur.AMPHUR_NAME FROM " . self::TABLE . " JOIN province ON " . self::TABLE . ".PROVINCE_ID = province.PROVINCE_ID JOIN amphur ON " . self::TABLE . ".AMPHUR_ID = amphur.AMPHUR_ID " ; // echo $query;exit(); $stmt = $con->prepare($query); $stmt->setFetchMode(PDO::FETCH_CLASS, "Company"); $stmt->execute(); $companyList = array(); while ($prod = $stmt->fetch()) { $companyList[$prod->getID_Company()] = $prod; } return $companyList; } public static function findById(int $ID_Company): ?Company { $con = Db::getInstance(); $query = "SELECT * FROM " . self::TABLE . " WHERE ID_Company = '$ID_Company'"; $stmt = $con->prepare($query); $stmt->setFetchMode(PDO::FETCH_CLASS, "Company"); $stmt->execute(); if ($prod = $stmt->fetch()) { return $prod; } return null; } # จัดการบริษัทลูกค้า ( เพิ่มบริษัทลูกค้า ) public function create_company(array $params) { $con = Db::getInstance(); $values = ""; $columns = ""; foreach ($params as $prop => $val) { # ถ้า column แรกไม่ต้องเติมลูกน้ำ คอลัมน์อื่นเติมลูกน้ำ $columns = empty($columns) ? $columns .= $prop : $columns .= "," . $prop; $values .= "'$val',"; } $values = substr($values, 0, -1); $query = "INSERT INTO " . self::TABLE . "({$columns}) VALUES ($values)"; # execute query if ($con->exec($query)) { return array("status" => true); } else { $message = "มีบางอย่างผิดพลาด , กรุณาตรวจสอบข้อมูล "; return array("status" => false, "message" => $message); } } # จัดกาบริษัทลูกค้า ( เพิ่มบริษัทลูกค้า excel ) public function create_company_at_once(array $params) { $con = Db::getInstance(); // turn off auto commit (ปิดคำสั่งสำหรับการยืนยันการเปลี่ยนแปลงข้อมูลที่เกิดขึ้น) $con->beginTransaction(); foreach ($params as $k => $v) { $values = ""; $columns = ""; foreach ($v as $prop => $val) { # ถ้า column แรกไม่ต้องเติมลูกน้ำ คอลัมน์อื่นเติมลูกน้ำ .. $columns = empty($columns) ? $columns .= $prop : $columns .= "," . $prop; $values .= "'$val',"; } #เช็คว่ามี ID ส่งมาไหม if (!isset($v['ID_Company'])) { $con->rollBack(); $message = "มีบางอย่างผิดพลาด , ไอดีบริษัทลูกค้าไม่สามารถเป็นค่าว่างได้ "; return array("status" => false, "message" => $message); } #ตรวจสอบรายการที่ซ้ำกัน $check_duplicate = Company::findById($v['ID_Company']); if (!empty($check_duplicate)) { # rollback when got error (เมื่อ error ให้ยกเลิกการเปลี่ยนแปลงข้อมูลที่เกิดขึ้น) $con->rollBack(); $message = "มีบางอย่างผิดพลาด , มีไอดีบริษัทลูกค้า {$v['ID_Company']} ในระบบเเล้ว"; return array("status" => false, "message" => $message); } # insert ลง db $values = substr($values, 0, -1); $query = "INSERT INTO " . self::TABLE . "({$columns}) VALUES ($values)"; //echo $query;exit(); # execute query if ($con->exec($query)) { # do something } else { # rollback when got error $con->rollBack(); $message = "มีบางอย่างผิดพลาด , กรุณาตรวจสอบข้อมูล "; return array("status" => false, "message" => $message); } } # commit $con->commit(); return array("status" => true); } public function file_log(string $file_name, int $id) { $query = "UPDATE file_log SET file_name = '{$file_name}' where id = {$id} "; //echo $query;exit(); $con = Db::getInstance(); if ($con->exec($query)) { return array("status" => true); } } # แก้ไข company public function edit_company(array $params, string $ID_Company) { $query = "UPDATE " . self::TABLE . " SET "; foreach ($params as $prop => $val) { $query .= " $prop='$val',"; } $query = substr($query, 0, -1); $query .= " WHERE ID_Company = '" . $ID_Company . "'"; //echo $query;exit(); $con = Db::getInstance(); if ($con->exec($query)) { return array("status" => true); } else { return array("status" => false); } } # ลบ company public function delete_company($ID_Company) { $query = "DELETE FROM " . self::TABLE . " WHERE ID_Company = '{$ID_Company}' "; $con = Db::getInstance(); if ($con->exec($query)) { return array("status" => true); } else { return array("status" => false); } } public function export_excel(string $page) { } public function getAmphur(int $PROVINCE_ID){ $con = Db::getInstance(); $query = "SELECT * FROM amphur WHERE PROVINCE_ID = '$PROVINCE_ID'"; //echo $query;exit(); $stmt = $con->prepare($query); $stmt->setFetchMode(PDO::FETCH_CLASS, "amphur"); $stmt->execute(); $returndata = array(); if ($prod = $stmt->fetch()) { while ($prod = $stmt->fetch()) { $array_pushs = array("AMPHUR_ID" => $prod->getAMPHUR_ID() , "AMPHUR_CODE" => $prod->getAMPHUR_CODE() , "AMPHUR_NAME" => $prod->getAMPHUR_NAME() , "PROVINCE_ID" => $prod->getPROVINCE_ID()); array_push($returndata , $array_pushs); } } if(!empty($returndata)){ return $returndata; }else{ return null; } } } ?><file_sep><html> <head> <link rel="stylesheet" href="AdminLTE/plugins/sweetalert2/sweetalert2.min.css"> <script src="AdminLTE/plugins/sweetalert2/sweetalert2.all.min.js"></script> </head> <body> <div id=""> </div> <script type='text/javascript'> Swal.fire({ icon: 'error', title: 'ขออภัย ...', text: <?= $_GET["message"] ?>, }).then((result) => { window.history.back(); }); </script> </body> </html><file_sep><?php class NewsController { /** * handleRequest จะทำการตรวจสอบ action และพารามิเตอร์ที่ส่งเข้ามาจาก Router * แล้วทำการเรียกใช้เมธอดที่เหมาะสมเพื่อประมวลผลแล้วส่งผลลัพธ์กลับ * * @param string $action ชื่อ action ที่ผู้ใช้ต้องการทำ * @param array $params พารามิเตอร์ที่ใช้เพื่อในการทำ action หนึ่งๆ */ public function handleRequest(string $action = "index", array $params) { switch ($action) { case "index": $this->index(); break; case "manage_news" : $this->$action(); break; case "create_news" : $ID_Employee = isset($params["GET"]["ID_Employee"]) ? $params["GET"]["ID_Employee"] : ""; $FILE_IMG = isset($params["FILES"]["profile_news"]) ? $params["FILES"]["profile_news"] : ""; $result = $this->$action($params["POST"], $FILE_IMG, $ID_Employee); echo $result; break; case "findbyID_Message": $ID_Message = isset($params["POST"]["ID_Message"]) ? $params["POST"]["ID_Message"] : ""; if (!empty($ID_Message)) { $result = $this->$action($ID_Message); echo $result; } break; case "edit_news": $FILE_IMG = isset($params["FILES"]) ? $params["FILES"] : ""; $Params= isset($params["POST"]) ? $params["POST"] : ""; $ID_Message = isset($params["GET"]["ID_Message"]) ? $params["GET"]["ID_Message"] : ""; $result = $this->$action($params["POST"] ,$FILE_IMG, $ID_Message); echo $result; break; case "delete_news": $params = isset($params["GET"]["ID_Message"]) ? $params["GET"]["ID_Message"] : ""; $result = $this->$action($params); // print_r($params); echo $result; break; case "show_news_status": session_start(); $employee = $_SESSION['employee']; if ($employee->getUser_Status_Employee() == "Admin") { include Router::getSourcePath() . "views/index_admin.inc.php"; } else if ($employee->getUser_Status_Employee() == "Sales") { # retrieve data $message = Message::fetchAllwithInner($employee->getID_Employee()); $countAll = Message::fetchCountAll($employee->getID_Employee()); include Router::getSourcePath() . "views/sales/index_news.inc.php"; } else if ($employee->getUser_Status_Employee() == "User") { # retrieve data $message = Message::fetchAllwithInner($employee->getID_Employee()); $countAll = Message::fetchCountAll($employee->getID_Employee()); include Router::getSourcePath() . "views/user/index_news.inc.php"; } break; case "update_status_news": session_start(); $employee = $_SESSION['employee']; $ID_Message = isset($params["GET"]["ID_Message"]) ? $params["GET"]["ID_Message"] : ""; if ($employee->getUser_Status_Employee() == "Admin") { include Router::getSourcePath() . "views/index_admin.inc.php"; } else if ($employee->getUser_Status_Employee() == "Sales") { # retrieve data $message = Message::update_news_status($employee->getID_Employee(), $ID_Message); include Router::getSourcePath() . "views/sales/redirect_index_news.inc.php"; } else if ($employee->getUser_Status_Employee() == "User") { # retrieve data $message = Message::update_news_status($employee->getID_Employee(), $ID_Message); include Router::getSourcePath() . "views/user/redirect_index_news.inc.php"; } break; default: break; } } private static function create_news($params, $FILE_IMG, $emp_id) { // # สร้างข่าวสารร $access_news = new Message(); $messageid = $access_news->geneateDateTimemd() ; $message_title = $params["Tittle_Message"] ; $message_text = isset($params["Text_Message"]) ? $params["Text_Message"] : ""; // print_r('hello world'. ' ' . $access_news->generatePictureFilename($FILE_IMG['name'][0], $message_title)); $message_filename = !empty($FILE_IMG) ? $access_news->generatePictureFilename($FILE_IMG['name'][0], $message_title) : "" ; $message_datetime = $access_news->geneateDateTime(); $locate_img = ""; if (!empty($FILE_IMG) && !empty($FILE_IMG['name'])) { $name_file = $FILE_IMG['name'][0]; $name_file_type = explode('.',$name_file)[1] ; $tmp_name = $FILE_IMG['tmp_name'][0]; $locate_img = Router::getSourcePath() . "images/" . $message_filename . ".".$name_file_type; // copy original file to destination file move_uploaded_file($tmp_name, $locate_img); } $access_news_params = array( "ID_Message" => $messageid, "Tittle_Message" => $message_title, "Text_Message" => $message_text, "Picture_Message" => $locate_img, "Date_Message"=> $message_datetime, ); $result = $access_news->create_news( $access_news_params, $emp_id ); return json_encode($result); } private function findbyID_Message($findbyID_Message) { $message = Message::findById($findbyID_Message);//echo json_encode($employee); // echo json_encode(array("data" => $data_sendback)); $data_sendback = array( "ID_Message" => $message->getID_Message(), "Tittle_Message" => $message->getTittle_Message(), "Text_Message" => $message->getText_Message(), "Picture_Message" => $message->getPicture_Message(), "Date_Message" => $message->getDate_Message(), ); echo json_encode(array("data" => $data_sendback)); } private function edit_news($params, $FILE_IMG, $ID_Message) { // # สร้างข่าวสารร $access_news = new Message(); $messageid = $ID_Message ; $message_title = $params["Tittle_Message"] ; $message_text = isset($params["Text_Message"]) ? $params["Text_Message"] : ""; $message_datetime = $access_news->geneateDateTime(); $locate_img = ""; // print_r('hello world'. ' ' . $access_news->generatePictureFilename($FILE_IMG['profile_news']['name'][0], $message_title)); $message_filename = !empty($FILE_IMG) ? $access_news->generatePictureFilename($FILE_IMG['profile_news']['name'][0], $message_title) : "" ; if (!empty($FILE_IMG) && !empty($FILE_IMG['profile_news']['name'])) { $name_file = $FILE_IMG['profile_news']['name'][0]; $name_file_type = explode('.',$name_file)[1] ; $tmp_name = $FILE_IMG['profile_news']['tmp_name'][0]; $locate_img = Router::getSourcePath() . "images/" . $message_filename . ".".$name_file_type; // copy original file to destination file move_uploaded_file($tmp_name, $locate_img); } $access_news_params = array( "ID_Message" => $messageid, "Tittle_Message" => $message_title, "Text_Message" => $message_text, "Picture_Message" => $locate_img, "Date_Message"=> $message_datetime, ); $result = $access_news->update_news( $access_news_params ); return json_encode($result); } private function delete_news($params) { $access_message = new Message(); $result = $access_message->delete_news( $params ); return json_encode($result); } private function error_handle(string $message) { $this->index($message); } // ควรมีสำหรับ controller ทุกตัว private function index($message = null) { session_start(); $employee = $_SESSION["employee"]; include Router::getSourcePath() . "views/index_admin.inc.php"; } //หน้าจัดการข่าวสาร private function manage_news($params = null) { session_start(); $employee = $_SESSION["employee"]; # retrieve data $employeeList = Employee::findAll(); $message = Message::fetchAll(); include Router::getSourcePath() . "views/admin/manage_news.inc.php"; } }<file_sep><?php $title = "S Super Cable"; try { if (!isset($_SESSION['employee']) || !is_a($_SESSION['employee'], "Employee")) { header("Location: " . Router::getSourcePath() . "index.php"); } ob_start(); ?> <!-- Navbar --> <nav class="main-header navbar navbar-expand navbar-white navbar-light"> <!-- Left navbar links --> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" data-widget="pushmenu" href="#" role="button"><i class="fas fa-bars"></i></a> </li> </ul> <!-- Right navbar links --> <ul class="navbar-nav ml-auto"> </ul> </nav> <!-- /.navbar --> <div class=" content-wrapper"> <!-- Content Header (Page header) --> <div class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> <h1 class="m-0">แดชบอร์ด </h1> <?php include Router::getSourcePath() . "views/admin/dashboard.inc.php" ?> </div><!-- /.col --> </div><!-- /.row --> </div><!-- /.container-fluid --> </div> <!-- /.content-header --> </div> <!-- /.content-wrapper --> <!-- Main Sidebar Container --> <aside class="main-sidebar sidebar-dark-primary elevation-4"> <!-- Brand Logo --> <a class="brand-link"> <img src="AdminLTE/dist/img/AdminLTELogo.png" alt="AdminLTE Logo" class="brand-image img-circle elevation-3" style="opacity: .8"> <span class="brand-text font-weight-light">S Super Cable</span> </a> <!-- Sidebar --> <?php include Router::getSourcePath() . "templates/admin/sidebar_menu.inc.php"; ?> <!-- /.sidebar --> </aside> <?php # modal dialog ( edit profile ) include Router::getSourcePath() . "views/modal/modal_editprofile.inc.php"; ?> <footer class="main-footer"> <strong>Copyright &copy; 2014-2021 <a href="https://adminlte.io">AdminLTE.io</a>.</strong> All rights reserved. <div class="float-right d-none d-sm-inline-block"> <b>Version</b> 3.1.0-rc </div> </footer> </div> <?php $content = ob_get_clean(); include Router::getSourcePath() . "templates/layout.php"; } catch (Throwable $e) { // PHP 7++ echo "การเข้าถึงถูกปฏิเสธ: ไม่ได้รับอนุญาตให้ดูหน้านี้"; exit(1); } ?> <file_sep><div class="sidebar"> <!-- Sidebar user panel (optional) --> <?php include("templates/sidebar_profile.inc.php"); ?> <!-- Sidebar Menu --> <nav class="mt-2"> <ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false"> <!-- Add icons to the links using the .nav-icon class with font-awesome or any other icon font library --> <li class="nav-item menu-open"> <a class="nav-link active"> <i class="nav-icon fas fa-tachometer-alt"></i> <p> หน้าหลัก <i class="right fas fa-angle-left"></i> </p> </a> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="index.php?controller=Homepage&action=index" class="nav-link"> <i class="nav-icon fas fa-tachometer-alt"></i> <p> หน้าหลัก </p> </a> </li> </ul> </li> <li class="nav-item menu-open"> <a class="nav-link active"> <i class="nav-icon fas fa-tasks"></i> <p> จัดการ <i class="right fas fa-angle-left"></i> </p> </a> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="<?php echo Router::getSourcePath() . "index.php?controller=Admin&action=manage_user"; ?>" class="nav-link"> <i class="nav-icon fas fa-users"></i> <p> ผู้ใช้ </p> </a> </li> </ul> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="pages/zone.html" class="nav-link"> <i class="nav-icon fas fa-network-wired"></i> <p> โซนพนักงาน </p> </a> </li> </ul> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="<?php echo Router::getSourcePath() . "index.php?controller=Company&action=manage_company"; ?>" class="nav-link"> <i class="nav-icon fas fa-store"></i> <p> บริษัท </p> </a> </li> </ul> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="<?php echo Router::getSourcePath() . "index.php?controller=File&action=manage_file"; ?>" class="nav-link"> <i class="nav-icon fas fa-file"></i> <p> เอกสาร </p> </a> </li> </ul> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="<?php echo Router::getSourcePath() . "index.php?controller=Goods&action=manage_goods"; ?>" class="nav-link"> <i class="nav-icon fas fa-boxes"></i> <p> สินค้า </p> </a> </li> </ul> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="<?php echo Router::getSourcePath() . "index.php?controller=Promotion&action=manage_promotion"; ?>" class="nav-link"> <i class="nav-icon fas fa-gifts"></i> <p> สินค้าส่งเสริมการขาย </p> </a> </li> </ul> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="<?php echo Router::getSourcePath() . "index.php?controller=News&action=manage_news"; ?>" class="nav-link"> <i class="nav-icon fas fa-comments"></i> <p> ข่าวสาร </p> </a> </li> </ul> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="<?php echo Router::getSourcePath() . "index.php?controller=Award&action=manage_award"; ?>" class="nav-link"> <i class=" nav-icon fas fa-award"></i> <p> รางวัล </p> </a> </li> </ul> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="pages/quotation.html" class="nav-link"> <i class="nav-icon fas fa-file-invoice"></i> <p> ใบเสนอราคา </p> </a> </li> </ul> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="<?php echo Router::getSourcePath() . "index.php?controller=ResultSales&action=manage_sales"; ?>" class="nav-link"> <i class="nav-icon fas fa-wallet"></i> <p>ยอดขาย </p> </a> </li> </ul> </li> <li class="nav-item menu-open"> <a class="nav-link active"> <i class="nav-icon fas fa-gift"></i> <p> เบิก/คืน <i class="right fas fa-angle-left"></i> </p> </a> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="pages/promotion.html" class="nav-link"> <i class="nav-icon fas fa-gift "></i> <p> ส่งเสริมการขาย </p> </a> </li> </ul> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="pages/promotion.html" class="nav-link"> <i class="nav-icon fas fa-history "></i> <p> ประวัติการอนุมัติ </p> </a> </li> </ul> </li> <li class="nav-item menu-open"> <a class="nav-link active"> <i class="nav-icon fas fa-chart-pie"></i> <p> รายงาน <i class="right fas fa-angle-left"></i> </p> </a> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="./index.html" class="nav-link"> <i class="nav-icon fas fa-store"></i> <p>เปอร์เซ็นของกลุ่มลูกค้า </p> </a> </li> </ul> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="./index.html" class="nav-link"> <i class="nav-icon fas fa-store"></i> <p>ลูกค้าที่ไม่เคลื่อนไหว </p> </a> </li> </ul> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="./index.html" class="nav-link"> <i class="nav-icon fas fa-file"></i> <p>เอกสาร </p> </a> </li> </ul> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="./index.html" class="nav-link"> <i class="nav-icon fas fa-wallet"></i> <p>ยอดขายเเต่ละคน</p> </a> </li> </ul> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="./index.html" class="nav-link"> <i class="nav-icon fas fa-wallet"></i> <p>เปรียบเทียบยอดขาย</p> </a> </li> </ul> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="./index.html" class="nav-link"> <i class="nav-icon fas fa-wallet "></i> <p>แนวโน้มยอดขาย </p> </a> </li> </ul> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="./index.html" class="nav-link"> <i class="nav-icon fas fa-gift "></i> <p>ส่งเสริมการขาย </p> </a> </li> </ul> </li> <li class="nav-item menu-open"> <a class="nav-link active"> <i class="nav-icon fas fa-sign-out-alt"></i> <p> ออกจากระบบ <i class="right fas fa-angle-left"></i> </p> </a> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="#" onclick="logout()" class="nav-link"> <i class="nav-icon fas fa-sign-out-alt"></i> <p>ออกจากระบบ </p> </a> </li> </ul> </li> </ul> </nav> <!-- /.sidebar-menu --> </div><file_sep><?php class HomepageController { /** * handleRequest จะทำการตรวจสอบ action และพารามิเตอร์ที่ส่งเข้ามาจาก Router * แล้วทำการเรียกใช้เมธอดที่เหมาะสมเพื่อประมวลผลแล้วส่งผลลัพธ์กลับ * * @param string $action ชื่อ action ที่ผู้ใช้ต้องการทำ * @param array $params พารามิเตอร์ที่ใช้เพื่อในการทำ action หนึ่งๆ */ public function handleRequest(string $action = "index", array $params) { switch ($action) { case "index": session_start(); $employee = $_SESSION['employee']; if ($employee->getUser_Status_Employee() == "Admin") { # find all employee $user_count = count(Employee::findAll()); include Router::getSourcePath() . "views/index_admin.inc.php"; } else if ($employee->getUser_Status_Employee() == "Sales") { include Router::getSourcePath() . "views/index_sales.inc.php"; } else if ($employee->getUser_Status_Employee() == "User") { include Router::getSourcePath() . "views/index_user.inc.php"; } break; default: break; } } private function error_handle(string $message) { $this->index($message); } // ควรมีสำหรับ controller ทุกตัว private function index($message) { include Router::getSourcePath() . "views/error_handle.inc.php"; } }<file_sep><?php class Router { //--------------- Properties private $controller; // target controller private $action; // action ที่ให้ทำใน controller นั้น private $file; // ไฟล์ที่อยู่ของ target controller /** * @var array ข้อมูลที่ส่งมาจากผู้ใช้เพื่อใช้ในการทำงาน โดยมีโครงสร้างเป็น assoc array แบบ 2 มิติ * "GET" => assoc array ที่ผู้ใช้ส่งผ่านตัวแปร $_GET * "POST" => assoc array ที่ผู้ใช้ส่งผ่านตัวแปร $_POST */ private $params; private static $sourcePath; // path ของไฟล์ที่เรียกใช้ router เทียบกับ root folder //--------------- Constructor public function __construct(string $path) { self::$sourcePath = $path; } //--------------- Methods public static function getSourcePath(): string { return self::$sourcePath; } public function load() { $this->getController(); $class = $this->controller . "Controller"; $controller = new $class(); // Call action of target controller $controller->handleRequest($this->action, $this->params); } private function getController() { $this->controller = $_GET['controller'] ?? "Index"; $this->action = $_GET['action'] ?? "index"; $this->file = "./controllers/" . $this->controller . "Controller.class.php"; $this->params["GET"] = $_GET; $this->params["POST"] = $_POST; if (isset($_FILES)) { $this->params["FILES"] = $_FILES; } } }<file_sep><!-- Sidebar --> <div class="sidebar"> <!-- Sidebar user panel (optional) --> <?php include("templates/sidebar_profile.inc.php"); ?> <!-- Sidebar Menu --> <nav class="mt-2"> <ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false"> <!-- Add icons to the links using the .nav-icon class with font-awesome or any other icon font library --> <li class="nav-item menu-open"> <a class="nav-link active"> <i class="nav-icon fas fa-tachometer-alt"></i> <p> หน้าหลัก <i class="right fas fa-angle-left"></i> </p> </a> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="index.php?controller=Homepage&action=index" class="nav-link"> <i class="nav-icon fas fa-tachometer-alt"></i> <p> หน้าหลัก </p> </a> </li> </ul> </li> <li class="nav-item menu-open"> <a class="nav-link active"> <i class="nav-icon fas fa-tasks"></i> <p> จัดการ <i class="right fas fa-angle-left"></i> </p> </a> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="pages/company.html" class="nav-link"> <i class="nav-icon fas fa-file-invoice"></i> <p> เสนอราคา </p> </a> </li> </ul> </li> <li class="nav-item menu-open"> <a class="nav-link active"> <i class="nav-icon fas fa-gift"></i> <p> เบิก/คืน <i class="right fas fa-angle-left"></i> </p> </a> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="pages/company.html" class="nav-link"> <i class="nav-icon fas fa-gifts"></i> <p> ส่งเสริมการขาย </p> </a> </li> </ul> </li> <li class="nav-item menu-open"> <a class="nav-link active"> <i class="nav-icon fas fa-eye"></i> <p> เเสดงผล <i class="right fas fa-angle-left"></i> </p> </a> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="<?php echo Router::getSourcePath() . "index.php?controller=News&action=show_news_status"; ?>" class="nav-link"> <i class="nav-icon fas fa-comment"></i> <p> ข่าวสาร </p> </a> </li> </ul> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="<?php echo Router::getSourcePath() . "index.php?controller=Award&action=show_award_status"; ?>" class="nav-link"> <i class="nav-icon fas fa-award"></i> <p> รางวัล </p> </a> </li> </ul> <li class="nav-item menu-open"> <a class="nav-link active"> <i class="nav-icon fas fa-chart-pie"></i> <p> รายงาน <i class="right fas fa-angle-left"></i> </p> </a> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="pages/company.html" class="nav-link"> <i class="nav-icon fas fa-wallet"></i> <p> เปรียบเทียบยอดขาย </p> </a> </li> </ul> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="pages/company.html" class="nav-link"> <i class="nav-icon fas fa-wallet"></i> <p> เปรียบเทียบรายได้ </p> </a> </li> </ul> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="pages/company.html" class="nav-link"> <i class="nav-icon fas fa-file"></i> <p> ประวัติลูกค้า </p> </a> </li> </ul> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="pages/company.html" class="nav-link"> <i class="nav-icon fas fa-store"></i> <p> ลูกค้าที่ไม่เคลื่อนไหว </p> </a> </li> </ul> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="pages/company.html" class="nav-link"> <i class="nav-icon fas fa-file"></i> <p> ไฟล์สเปกสินค้า </p> </a> </li> </ul> </li> <li class="nav-item menu-open"> <a class="nav-link active"> <i class="nav-icon fas fa-sign-out-alt"></i> <p> ออกจากระบบ <i class="right fas fa-angle-left"></i> </p> </a> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="#" onclick="logout()" class="nav-link"> <i class="nav-icon fas fa-sign-out-alt"></i> <p>ออกจากระบบ </p> </a> </li> </ul> </li> </ul> </nav> <!-- /.sidebar-menu --> </div> <!-- /.sidebar --> <file_sep><div class="sidebar"> <?php // echo '<PRE>'; // print_r($_SESSION);exit(); ?> <!-- Sidebar user panel (optional) --> <div class="user-panel mt-3 pb-3 mb-3 d-flex"> <div class="image"> <img src="<?php echo empty($employee->Picuture_Employee) ? "AdminLTE/dist/img/no_img.png" : "images/" . $employee->Picuture_Employee; ?>" class="img-circle elevation-2" alt="User Image"> </div> <div class="info"> <a href="#" onclick="showModalEditProfile()" class="d-block"><?php echo $employee->getName_Employee() . " " . $employee->getSurname_Employee(); ?></a> </div> </div><file_sep><?php header("Location: " . Router::getSourcePath() . "index.php?controller=Award&action=show_award_status"); ?> <file_sep><?php # excel library include Router::getSourcePath() . 'classes/Excel.class.php'; class AdminController { /** * handleRequest จะทำการตรวจสอบ action และพารามิเตอร์ที่ส่งเข้ามาจาก Router * แล้วทำการเรียกใช้เมธอดที่เหมาะสมเพื่อประมวลผลแล้วส่งผลลัพธ์กลับ * * @param string $action ชื่อ action ที่ผู้ใช้ต้องการทำ * @param array $params พารามิเตอร์ที่ใช้เพื่อในการทำ action หนึ่งๆ */ public function handleRequest(string $action = "index", array $params) { switch ($action) { case "index": $this->index(); break; case "manage_user" : $this->$action(); break; case "create_user" : $result = $this->$action($params["POST"]); echo $result; break; case "edit_user" : $ID_Employee = isset($params["GET"]["ID_Employee"]) ? $params["GET"]["ID_Employee"] : ""; $result = $this->$action($params["POST"], $ID_Employee); echo $result; break; case "delete_user": $result = $this->$action($params["POST"]["ID_Employee"]); echo $result; break; case "import_excel_user": $FILES = isset($params["FILES"]["file"]) ? $params["FILES"]["file"] : ""; $FILE_IMG = isset($params["FILES"]["examfile"]) ? $params["FILES"]["examfile"] : ""; $result = $this->$action($params["POST"], $FILES, $FILE_IMG); echo $result; break; case "export_excel_test_user": $result = $this->$action($params["POST"]); echo $result; break; case "export_excel_user": $result = $this->$action($params["POST"]); echo $result; break; case "export_excel_test_company": $result = $this->$action($params["POST"]); echo $result; break; default: break; } } private function import_excel_user(array $params, array $FILES, array $FILE_IMG) { $excel = new Excel(); #UPLOAD IMAGE if (!empty($FILE_IMG) && !empty($FILE_IMG['name'])) { # update new pic $target_file_img = Router::getSourcePath() . "images/" . $FILE_IMG['name']; if (!empty($FILE_IMG) && isset($FILE_IMG['name'])) { if (!empty($FILE_IMG['name'])) { move_uploaded_file($FILE_IMG["tmp_name"], $target_file_img); $employee_ = new Employee(); $employee_->file_log($FILE_IMG['name'], 1); } } } #UPLOAD EXCEL if (!empty($FILES) && !empty($FILES['name'])) { $path = $FILES["tmp_name"]; $object = PHPExcel_IOFactory::load($path); $params = array(); //case: การอัพโหลดไฟล์ excel ถ้าลืมใส่ column ไหนให้บอกผิด row ไหน $EXCEL_HeaderCol = array("ID_Employee" => array("name" => "ไอดีพนักงาน", "status" => false, "error" => "ไม่พบข้อมูลคอลัมน์ ไอดีพนักงาน") , "Name_Employee" => array("name" => "ชื่อพนักงาน", "status" => false, "error" => "ไม่พบข้อมูลคอลัมน์ ชื่อพนักงาน") , "Surname_Employee" => array("name" => "นามสกุลพนักงาน", "status" => false, "error" => "ไม่พบข้อมูลคอลัมน์ นามสกุลพนักงาน") , "Username_Employee" => array("name" => "ชื่อผุ้ใช้", "status" => false, "error" => "ไม่พบข้อมูลคอลัมน์ ชื่อผุ้ใช้") , "Email_Employee" => array("name" => "อีเมล์", "status" => false, "error" => "ไม่พบข้อมูลคอลัมน์ อีเมล์") , "Password_Employee" => array("name" => "รหัสผ่าน", "status" => false, "error" => "ไม่พบข้อมูลคอลัมน์ รหัสผ่าน") , "User_Status_Employee" => array("name" => "สถานะ", "status" => false, "error" => "ไม่พบข้อมูลคอลัมน์ สถานะ") ); $count = 0; foreach ($object->getWorksheetIterator() as $worksheet) { $highestRow = $worksheet->getHighestRow(); $highestColumn = $worksheet->getHighestColumn(); // echo $highestRow;exit(); // row = 2 คือ row แรก ไม่รวม header #เช็คหัวตารางชื่อตรงกันไหมใน array ที่ hardcode ไว้ if ($count != 1) { for ($col_ = 0; $col_ < 7; $col_++) { $col__cc = strval($worksheet->getCellByColumnAndRow($col_, 1)->getValue()); if ($col__cc == '') { $c = array_values($EXCEL_HeaderCol); $message = "มีบางอย่างผิดพลาด , กรุณาตรวจสอบข้อมูลไม่พบคอลัมน์ " . $c[$col_]['name']; return json_encode(array("status" => false, "message" => $message)); } else { $ccc = array_key_exists($col__cc, $EXCEL_HeaderCol); if (!$ccc) { $c = array_values($EXCEL_HeaderCol); $message = "มีบางอย่างผิดพลาด , กรุณาตรวจสอบข้อมูลไม่พบคอลัมน์ " . $c[$col_]['name']; return json_encode(array("status" => false, "message" => $message)); } } } ++$count; } #eof for ($row = 2; $row <= $highestRow; $row++) { if ($worksheet->getCellByColumnAndRow(0, $row)->getValue() != '') { $getCellArray = $this->checkemptycell_user($worksheet, $row); if ($getCellArray['status'] == false) { $c = array_values($EXCEL_HeaderCol); $message = "มีบางอย่างผิดพลาด , กรุณาตรวจสอบข้อมูลไม่พบข้อมูลในแถวที่{$row}(รวมหัวตาราง) ในคอลัมน์คือ " . $c[$getCellArray["column"]]['name'] . ''; return json_encode(array("status" => false, "message" => $message)); } $push_array = array("ID_Employee" => $getCellArray["data"][0], "Name_Employee" => $getCellArray["data"][1], "Surname_Employee" => $getCellArray["data"][2], "Username_Employee" => $getCellArray["data"][3], "Email_Employee" => $getCellArray["data"][4], "Password_Employee" => $getCellArray["data"][5], "User_Status_Employee" => $getCellArray["data"][6] ); array_push($params, $push_array); } else { $getCellArray = $this->checkemptycell_user($worksheet, $row); if ($getCellArray['status'] == false) { $c = array_values($EXCEL_HeaderCol); $message = "มีบางอย่างผิดพลาด , กรุณาตรวจสอบข้อมูลไม่พบข้อมูลในแถวที่{$row}(รวมหัวตาราง) ในคอลัมน์คือ " . $c[$getCellArray["column"]]['name'] . ''; return json_encode(array("status" => false, "message" => $message)); } } } } // # create user ใหม่ $employee_ = new Employee(); $result = $employee_->create_user_at_once($params); # update new pic $target_file = Router::getSourcePath() . "uploads/" . $FILES['name']; if (!empty($FILES) && isset($FILES['name'])) { if (!empty($FILES['name'])) { move_uploaded_file($FILES["tmp_name"], $target_file); } } return json_encode($result); } # return json_encode(array("status" => true)); } private function checkemptycell_user($worksheet, $row) { $push_array = array(); for ($i = 0; $i < 7; $i++) { if (empty($worksheet->getCellByColumnAndRow($i, $row)->getValue())) { return array("status" => false, "column" => $i, "row" => $row); } else { $push_array[$i] = $worksheet->getCellByColumnAndRow($i, $row)->getValue(); } } return array("status" => true, "data" => $push_array); } private function error_handle(string $message) { $this->index($message); } private function create_user($params) { # สร้างผู้ใช้ $access_employee = new Employee(); $employee_result = $access_employee->create_user( $params ); return json_encode($employee_result); } private function edit_user($params, $employee_id) { # อัปเดตผู้ใช้ $access_employee = new Employee(); $employee_result = $access_employee->edit_user( $params, $employee_id ); return json_encode($employee_result); } private function delete_user($ID_Employee) { # ลบผู้ใช้ $access_employee = new Employee(); $employee_result = $access_employee->delete_user( $ID_Employee ); return json_encode($employee_result); } // ควรมีสำหรับ controller ทุกตัว private function index($message = null) { session_start(); $employee = $_SESSION["employee"]; include Router::getSourcePath() . "views/index_admin.inc.php"; } //หน้าจัดการผู้ใช้ private function manage_user($params = null) { session_start(); $employee = $_SESSION["employee"]; # retrieve data $user = Employee::findAll(); $file_log = Filelog::findByPage('manage_user'); include Router::getSourcePath() . "views/admin/manage_user.inc.php"; } //หน้า export ไฟล์ตัวอย่าง excel ผู้ใช้ private function export_excel_test_user($params = null) { $exportExcel = new Employee(); $exportExcelEmployee = Employee::findAll(); try { // ob_end_clean(); // เรียนกใช้ PHPExcel $objPHPExcel = new PHPExcel(); // กำหนดค่าต่างๆ ของเอกสาร excel $objPHPExcel->getProperties()->setCreator("bp.com") ->setLastModifiedBy("bp.com") ->setTitle("PHPExcel Test Document") ->setSubject("PHPExcel Test Document") ->setDescription("Test document for PHPExcel, generated using PHP classes.") ->setKeywords("office PHPExcel php") ->setCategory("Test result file"); // กำหนดชื่อให้กับ worksheet ที่ใช้งาน $objPHPExcel->getActiveSheet()->setTitle('Report'); // กำหนด worksheet ที่ต้องการให้เปิดมาแล้วแสดง ค่าจะเริ่มจาก 0 , 1 , 2 , ...... $objPHPExcel->setActiveSheetIndex(0); // การจัดรูปแบบของ cell $objPHPExcel->getDefaultStyle() ->getAlignment() ->setVertical(PHPExcel_Style_Alignment::VERTICAL_TOP) ->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); //HORIZONTAL_CENTER //VERTICAL_CENTER // จัดความกว้างของคอลัมน์ $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20); $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20); $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20); $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20); $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20); $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20); $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20); // กำหนดหัวข้อให้กับแถวแรก $objPHPExcel->setActiveSheetIndex(0) ->setCellValue('A1', 'ID_Employee') ->setCellValue('B1', 'Name_Employee') ->setCellValue('C1', 'Surname_Employee') ->setCellValue('D1', 'Username_Employee') ->setCellValue('E1', 'Email_Employee') ->setCellValue('F1', '<PASSWORD>') ->setCellValue('G1', 'User_Status_Employee'); $start_row = 2; $objPHPExcel->setActiveSheetIndex(0) ->setCellValue('A' . $start_row, "x99") ->setCellValue('B' . $start_row, "firstname") ->setCellValue('C' . $start_row, "lastname") ->setCellValue('D' . $start_row, "username") ->setCellValue('E' . $start_row, "<EMAIL>") ->setCellValue('F' . $start_row, "example123E$") ->setCellValue('G' . $start_row, "Admin"); $i = 0; $filename = 'User-' . date("dmYHis") . '.xlsx'; // กำหนดชือ่ไฟล์ นามสกุล xls หรือ xlsx $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); // Excel2007 (xlsx) หรือ Excel5 (xls) ob_clean(); $objWriter->save('./uploads/' . $filename); //download header('Content-Type: application/octet-stream'); header("Content-Transfer-Encoding: Binary"); header("Content-disposition: attachment; filename=\"" . $filename . "\""); echo file_get_contents("./uploads/" . $filename); die; return json_encode(array('status' => true, "filename" => $filename)); //ob_end_clean(); // die($objWriter); //die; } catch (Exception $e) { // status that return to frontend $status = false; // error message handle $message = $e->getMessage(); } return json_encode(array('status' => true)); } //หน้า export ไฟล์ตัวอย่าง excel ผู้ใช้ private function export_excel_user($params = null) { $exportExcel = new Employee(); $exportExcelEmployee = Employee::findAll(); try { // เรียนกใช้ PHPExcel $objPHPExcel = new PHPExcel(); // กำหนดค่าต่างๆ ของเอกสาร excel $objPHPExcel->getProperties()->setCreator("bp.com") ->setLastModifiedBy("bp.com") ->setTitle("PHPExcel Test Document") ->setSubject("PHPExcel Test Document") ->setDescription("Test document for PHPExcel, generated using PHP classes.") ->setKeywords("office PHPExcel php") ->setCategory("Test result file"); // กำหนดชื่อให้กับ worksheet ที่ใช้งาน $objPHPExcel->getActiveSheet()->setTitle('Report'); // กำหนด worksheet ที่ต้องการให้เปิดมาแล้วแสดง ค่าจะเริ่มจาก 0 , 1 , 2 , ...... $objPHPExcel->setActiveSheetIndex(0); // การจัดรูปแบบของ cell $objPHPExcel->getDefaultStyle() ->getAlignment() ->setVertical(PHPExcel_Style_Alignment::VERTICAL_TOP) ->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); //HORIZONTAL_CENTER //VERTICAL_CENTER // จัดความกว้างของคอลัมน์ $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20); $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20); $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20); $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20); $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20); $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20); // กำหนดหัวข้อให้กับแถวแรก $objPHPExcel->setActiveSheetIndex(0) ->setCellValue('A1', 'ไอดีพนักงาน') ->setCellValue('B1', 'ชื่อ') ->setCellValue('C1', 'นามสกุล') ->setCellValue('D1', 'ชื่อผู้ใช้') ->setCellValue('E1', 'อีเมล์') ->setCellValue('F1', 'สถานะ'); $start_row = 2; if (!empty($exportExcelEmployee)) { $i = 0; foreach ($exportExcelEmployee as $i => $result_array) { // หากอยากจัดข้อมูลราคาให้ชิดขวา $objPHPExcel->getActiveSheet() ->getStyle('C' . $start_row) ->getAlignment() ->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); // หากอยากจัดให้รหัสสินค้ามีเลย 0 ด้านหน้า และแสดง 3 หลักเช่น 001 002 // $objPHPExcel->getActiveSheet() // ->getStyle('B'.$start_row) // ->getNumberFormat() // ->setFormatCode('000'); // เพิ่มข้อมูลลงแต่ละเซลล์ if (isset($exportExcelEmployee[$i])) { $objPHPExcel->setActiveSheetIndex(0) ->setCellValue('A' . $start_row, $exportExcelEmployee[$i]->getID_Employee()) ->setCellValue('B' . $start_row, $exportExcelEmployee[$i]->getName_Employee()) ->setCellValue('C' . $start_row, $exportExcelEmployee[$i]->getSurname_Employee()) ->setCellValue('D' . $start_row, $exportExcelEmployee[$i]->getUsername_Employee()) ->setCellValue('E' . $start_row, $exportExcelEmployee[$i]->getEmail_Employee()) ->setCellValue('F' . $start_row, $exportExcelEmployee[$i]->getUsername_Employee()); } ++$start_row; } // กำหนดรูปแบบของไฟล์ที่ต้องการเขียนว่าเป็นไฟล์ excel แบบไหน ในที่นี้เป้นนามสกุล xlsx ใช้คำว่า Excel2007 // แต่หากต้องการกำหนดเป็นไฟล์ xls ใช้กับโปรแกรม excel รุ่นเก่าๆ ได้ ให้กำหนดเป็น Excel5 ob_start(); $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); // Excel2007 (xlsx) หรือ Excel5 (xls) $filename = 'User-' . date("dmYHi") . '.xlsx'; // กำหนดชือ่ไฟล์ นามสกุล xls หรือ xlsx // บังคับให้ทำการดาวน์ดหลดไฟล์ header('Content-Type: application/vnd.ms-excel'); //mime type header('Content-Disposition: attachment;filename="' . $filename . '"'); //tell browser what's the file name header('Cache-Control: max-age=0'); //no cache ob_end_clean(); $objWriter->save('php://output'); // ดาวน์โหลดไฟล์รายงาน //die($objWriter); } else { // status that return to frontend $status = false; // error message handle $message = "ไม่พบข้อมูล"; } } catch (Exception $e) { // status that return to frontend $status = false; // error message handle $message = $e->getMessage(); } return json_encode(array('status' => true)); } }<file_sep><?php class Filelog { //------------- Properties private $ID; private $page; private const TABLE = "file_log"; //----------- Getters & Setters public function getID(): string { return $this->ID; } public function getPage(): string { return $this->page; } public function setID(string $ID) { $this->ID = $ID; } public function setPage(string $page) { $this->page = $page; } //----------- CRUD public static function findAll(): array { $con = Db::getInstance(); $query = "SELECT * FROM " . self::TABLE; $stmt = $con->prepare($query); $stmt->setFetchMode(PDO::FETCH_CLASS, "file_log"); $stmt->execute(); $filelogList = array(); while ($prod = $stmt->fetch()) { $filelogList[$prod->getID()] = $prod; } return $filelogList; } public static function findByPage(string $page) { $con = Db::getInstance(); $query = "SELECT * FROM " . self::TABLE . " WHERE page = '$page'"; $stmt = $con->prepare($query); $stmt->setFetchMode(PDO::FETCH_CLASS, "file_log"); $stmt->execute(); if ($prod = $stmt->fetch()) { return $prod; } return null; } } <file_sep><?php class Message { //------------- Properties private $ID_Message; private $Tittle_Message; private $Text_Message; private $Picture_Message; private $Date_Message; private $status; private $unread; private const TABLE = "message"; //----------- Getters & Setters public function getUnread(): int { return $this->unread; } public function setUnread(int $unread) { $this->$unread = $unread; } public function getStatus(): int { return $this->status; } public function setStatus(int $status) { $this->$status = $status; } // ---- id message public function getID_Message(): int { return $this->ID_Message; } public function setID_Message(int $ID_Message) { $this->ID_Message = $ID_Message; } // --- title message public function getTittle_Message(): string { return $this->Tittle_Message; } public function setTittle_Message(string $Tittle_Message) { $this->Tittle_Message = $Tittle_Message; } // - text message public function getText_Message(): string { return $this->Text_Message; } public function setText_Message(string $Text_Message) { $this->Text_Message = $Text_Message; } // --- picture message public function getPicture_Message(): string { return $this->Picture_Message; } public function setPicture_Message(string $Picture_Message) { $this->Picture_Message = $Picture_Message; } // --- date message public function getDate_Message(): string { return $this->Date_Message; } public function setDate_Message(string $Date_Message) { $this->Date_Message = $Date_Message; } //----------- CRUD public static function fetchCountAll($emp_id): array { $con = Db::getInstance(); $query = "select count(*) from message_status where status =0 and ID_Employee = '".$emp_id."'"; $stmt = $con->prepare($query); #$stmt->setFetchMode(PDO::FETCH_CLASS, "Message"); $stmt->execute(); #$list = array(); #while ($prod = $stmt->fetch()) { # $list[$prod->getID_Message()] = $prod; #} $prod = $stmt->fetch(); return $prod; #return $list; } public static function fetchAll(): array { $con = Db::getInstance(); $query = "SELECT * FROM " . self::TABLE; $stmt = $con->prepare($query); $stmt->setFetchMode(PDO::FETCH_CLASS, "Message"); $stmt->execute(); $list = array(); while ($prod = $stmt->fetch()) { $list[$prod->getID_Message()] = $prod; } return $list; } public static function fetchAllwithInner($emp_id): array { $con = Db::getInstance(); $query = "SELECT * FROM " . self::TABLE . " inner join message_status on message.ID_Message = message_status.ID_Message"." where message_status.ID_Employee = '".$emp_id."'"; $stmt = $con->prepare($query); $stmt->setFetchMode(PDO::FETCH_CLASS, "Message"); $stmt->execute(); $list = array(); while ($prod = $stmt->fetch()) { $list[$prod->getID_Message()] = $prod; } return $list; } public static function findById(int $ID_Message): ?Message { $con = Db::getInstance(); $query = "SELECT * FROM " . self::TABLE . " WHERE ID_Message = '$ID_Message'"; $stmt = $con->prepare($query); $stmt->setFetchMode(PDO::FETCH_CLASS, "Message"); $stmt->execute(); if ($prod = $stmt->fetch()) { return $prod; } return null; } public static function generateIDMessage($title_message) { $messageid = self::geneateDateTimemd() ; return md5(uniqid($messageid, true)) ; } public static function geneateDateTimemd() { return Date("YmdHis") ; } public static function geneateDateTime() { return date("Y-m-d H:i:s") ; } public static function generatePictureFilename($imagename, $titlemessage) { $message_picture_filename = "$imagename"."$titlemessage".self::geneateDateTimemd() ; return md5(uniqid($message_picture_filename, true)) ; } // save data to // insert data into server. public static function create_news($params, $emp_id) { $con = Db::getInstance(); $values = ""; $columns = ""; foreach ($params as $prop => $val) { # ถ้า column แรกไม่ต้องเติมลูกน้ำ คอลัมน์อื่นเติมลูกน้ำ $columns = empty($columns) ? $columns .= $prop : $columns .= "," . $prop; $values .= "'$val',"; } $values = substr($values, 0, -1); $query = "INSERT INTO " . self::TABLE . "({$columns}) VALUES ($values)"; # execute query if ($con->exec($query)) { $emp = new Employee(); $result = $emp->findAll(); # เข้า for loop เพือกระจาย status ของ news foreach ($result as $prop => $val) { $emp_id = $val->getID_Employee(); $con->exec("insert into message_status (ID_Employee, ID_Message) values('".$emp_id."',".$params['ID_Message'].")"); } return array("status" => true); } else { $message = "มีบางอย่างผิดพลาด , กรุณาตรวจสอบข้อมูล "; return array("status" => false, "message" => $message); } } // update data at database public static function update_news($params) { $ID_Message = $params['ID_Message']; $query = "UPDATE " . self::TABLE . " SET "; foreach ($params as $prop => $val) { if($val != '') { $query .= " $prop='$val',"; } } $query = substr($query, 0, -1); $query .= " WHERE ID_Message = '" . $ID_Message . "'"; $con = Db::getInstance(); if ($con->exec($query)) { return array("status" => true); } else { return array("status" => false); } } // update data at database public static function update_news_status($ID_Employee, $ID_Message) { //$ID_Message = $params['ID_Message']; $query = "UPDATE message_status SET status = 1 "; //$query = substr($query, 0, -1); $query .= " WHERE ID_Message = ".$ID_Message." and ID_Employee = '".$ID_Employee."'"; $con = Db::getInstance(); if ($con->exec($query)) { return array("status" => true); } else { return array("status" => false); } } // update data at database public static function update_award_status($ID_Employee, $ID_Award) { //$ID_Award = $params['ID_Award']; $query = "UPDATE message_status SET status = 1 "; //$query = substr($query, 0, -1); $query .= " WHERE ID_Award = ".$ID_Award." and ID_Employee = '".$ID_Employee."'"; $con = Db::getInstance(); if ($con->exec($query)) { return array("status" => true); } else { return array("status" => false); } } # ลบ company public function delete_news($ID_Message) { $query = "DELETE FROM " . self::TABLE . " WHERE ID_Message = '{$ID_Message}' "; $con = Db::getInstance(); if ($con->exec($query)) { return array("status" => true); } else { return array("status" => false); } } } <file_sep><?php $title = "S Super Cable"; try { ob_start(); ?> <!DOCTYPE html> <html lang="th"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body class="hold-transition login-page"> <div class="login-box"> <!-- /.login-logo --> <div class="card card-outline card-primary"> <div class="card-header text-center"> <a class="h1"><b>เข้าสู่ระบบ</b></a> </div> <div class="card-body"> <p class="login-box-msg">เข้าสู่ระบบเพื่อเริ่มเซสชัน</p> <form name="loginForm" id="loginForm" method="post" action=<?= Router::getSourcePath() . "index.php?controller=Employee&action=login" ?>> <div class="input-group mb-3"> <input type="username" class="form-control" placeholder="Username" name="Username_Employee" value="<?= isset($remember_me['Username_Employee']) ? $remember_me['Username_Employee'] : ""; ?>" id="Username_Employee"> <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-user"></span> </div> </div> </div> <div class="input-group mb-3"> <input type="<PASSWORD>" class="form-control" placeholder="<PASSWORD>" name="Password_Employee" value="<?= isset($remember_me['Password_Employee']) ? $remember_me['Password_Employee'] : ""; ?>" id="Password_Employee"> <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-lock"></span> </div> </div> </div> <div class="row"> <div class="col-8"> <div class="icheck-primary"> <input type="checkbox" id="RememberMe" name="RememberMe"> <label for="RememberMe"> จดจำฉัน </label> </div> </div> </div> <!-- /.col --> <div class="col-16"> <button type="submit" class="btn btn-primary btn-block">เข้าสู่ระบบ</button> </div> <!-- /.col --> </form> </div> <!-- /.card-body --> </div> <!-- /.card --> </div> <!-- /.login-box --> <?php $content = ob_get_clean(); include Router::getSourcePath() . "templates/layout.php"; } // -- try catch (Throwable $e) { ob_clean(); // ล้าง output เดิมที่ค้างอยู่จากการสร้าง page echo "การเข้าถึงถูกปฏิเสธ: ไม่ได้รับอนุญาตให้ดูหน้านี้"; exit(1); } ?> <file_sep><div class="modal fade" id="importsalesModal" tabindex="-1" role="dialog" aria-labelledby="importsalesModalDialog" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="importsalesModalTitle">นำเข้าไฟล์ excel</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form id="form_importexcel" method='post' action='' enctype="multipart/form-data"> <p>ตัวอย่าง format การนำข้อมูลเข้าระบบ</p> <img src="<?php echo Router::getSourcePath() . "images/" . $file_log['file_name'] ?>" width="100%"> <h6 class="pt-4">อัพโหลดไฟล์รูปภาพตัวอย่าง</h6> <input id="examfile" name="examfile" type="file" accept=".png, .jpg,.jpeg,.gif" style=""> <h6 class="pt-4">อัพโหลดไฟล์ Excel</h6> <input type="file" name="file" id="file" value="" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"/> </form> </div> <div class="modal-footer"> <a href="#" id="button_importsalesModal" data-status="" data-id="" class="btn btn-primary">ตกลง</a> <button type="button" class="btn btn-secondary" data-dismiss="modal">ยกเลิก</button> <a href="index.php?controller=ResultSales&action=export_excel_test_sales" <button type="button" class="btn btn-success" class="fa fa-file"></i> ดาวน์โหลดไฟล์ตัวอย่าง</span></button> </a> </div> </div> </div> </div>
b218a10285c0e99cc224834d912f43c15b5c5416
[ "Markdown", "PHP" ]
46
PHP
Amphol-Thiamnut/S-Super-Cable
75fd2163bd0369099d7cec334ac0cb71c3ca6bbe
a0228012fb6d3018b8c610b943340fd829e896dd
refs/heads/master
<file_sep>import {Router} from 'express' import {auth, home, users, devices} from './routes' const router = Router() export default function (options) { router.route('/login') .post(auth(options).login) router.route('/home') .get(Auth, home(options).home) router.route('/users') .get(Auth, users(options).read.all) .post(Auth, users(options).create) router.route('/users/:id') .get(Auth, users(options).read.one) .put(Auth, users(options).update) .delete(Auth, users(options).destroy) router.route('/devices') .get(Auth, devices(options).read.all) .post(Auth, devices(options).create) router.route('/devices/:id') .get(Auth, devices(options).read.one) .put(Auth, devices(options).update) .delete(Auth, devices(options).destroy) return router } function Auth (req, res, next) { if (req.session.user) { next() } else { res.status(401) .json({ message: 'Please log in...' }) } }
dbfde4d25b1d119887b65d14fa0d289f5fbf6628
[ "JavaScript" ]
1
JavaScript
shintech/express-seed
7fde971f126af540730c14b13af894d011a237e5
c2d369766460f851b9ccb3db3b0a624f32818196
refs/heads/master
<file_sep>#!/usr/bin/env python # # Call a Jenkins Server from AWS Lambda # # This isn't a complicated thing. All we need to do is get the incoming message, # figure out what needs to be called on Jenkins, fetch a crumb, and then do it. import requests def lambda_handler(event, context): source_arn = event['Records'][0]['eventSourceARN'] region = source_arn.split(":")[3] repository = source_arn.split(":")[5] url = 'http://<JENKINS_URI>/job/'+region+'/job/'+repository+'/build' call = requests.get('http://<JENKINS_URI>/crumbIssuer/api/json', auth=('<JENKINS_USER>', '<JENKINS_API_TOKEN>')) response = call.json() crumb = response.get('crumb') field = response.get('crumbRequestField') headers = {field:crumb} call = requests.post(url, headers=headers, auth=('<JENKINS_USER>', '<JENKINS_API_TOKEN>')) <file_sep># AWS-Jenkins-Connector You have AWS CodeCommit. You have Jenkins. You want them to work together. # What do you need? * Python 3.6 ``` pip install requests ``` * A recent Jenkins installation on an EC2 instance * Jenkins AWS CodeCommit Jobs plugin # What does it do? When using CodeCommit, you do not have access to pre-receive and post-receive server side hooks in `git`. The only thing available is to send a message to either a SNS topic, or call a Lambda function. In theory, you can use a Lambda function as your integration with just about any non-Amazon provided service. This also allows one to automate as much of the setup of Jenkins jobs as possible. # Yeah, this is dumb. Why not use Travis or CodeBuild? And for that matter, why not GitHub? AWS CodeBuild could be considered to be a bit....massive....for certain classes of projects (and for some, it flat out won't do what you want). Also, you have a very large amount of vendor lock-in, which may not be desirable for your use cases. Travis, and other cloud hosted CI/Source Control solutions are great (I even use them). However, not everyone in the world is able to use these solutions, thanks to the wonder of things called "Corporate IT Policy" # Okay, but what about Concourse CI? *sigh* Look, the main point here is not that Jenkins is the be-all end-all of CI tools, but rather that writing a glue function between Amazon's services (which want things done the Amazon Way™) and the rest of the world isn't that daunting. If you want to take what I've done and modify it to support Concourse CI, I'll be happy to host it here. # How do I set it up? You'll need to package the Python file along with the requests library, and upload it to a new AWS Lambda function. Make sure that your function policy allows CodeCommit to call it. Make sure you have Jenkins running, and have created a user who can start builds from the API (you'll need the API token). You will also want to have CodeCommit Jobs folders for each region that you have repositories in. Most importantly, you will want them named according to the AWS region short names (e.g. us-east-1). Once the region is indexed, any repositories that have a Jenkinsfile set up correctly will automatically have projects created for them. You can then go into the CodeCommit settings for the repo, and create a trigger to call the Lambda function. # That's it? Yup. You should have Jenkins building upon pushes to CodeCommit, which is as good as you will get with CodeCommit. # I want to contribute! How? * Fork this repository * Start your work in a new feature branch * Open a pull request
0330289f7cf20ed259c15b1b99116d2fbd6a4e96
[ "Markdown", "Python" ]
2
Python
KusabiSensei/AWS-Jenkins-Connector
2a4104bbbd283dd3d136637c0116876cd387d5b0
66ef1f4c344dce94d9b88d099862542cea7e8ac8
refs/heads/main
<file_sep># openapi2kt-dataclass This project attempts to parse a valid open-api json into Kotlin data classes ## How to use ``` node index.js path_to_openapi.json ./path/to/output/folder br.org.packagename.to.be.on.classes ```<file_sep>import capitalize from '../utils/capitalize.js' export default function parse2object(inputObject) { const schemaList = inputObject.components.schemas; var classes = {}; for(var schemaName in schemaList) { var schemaObj = schemaList[schemaName] if(schemaObj.type != "object" && !schemaObj.enum) { console.error("Schema " + schemaName + " is not an Object nor ENUM!"); continue; } initClass(classes, schemaName); classes[schemaName].fillClass(schemaObj); } return classes; } function initClass(classes, schemaName) { classes[schemaName] = { "name": schemaName, "properties": {}, "innerClasses": {}, "isEnum": false, "values": [], "fillClass": function(schemaObj) { if(schemaObj.type != "object" && schemaObj.enum) { this.isEnum = true; this.values = schemaObj.enum; return; } var properties = schemaObj.properties; for(var pName in properties) { var p = properties[pName]; initProperty(this, this.properties, pName); this.properties[pName].fillProperty(p); if(schemaObj.required && schemaObj.required.includes(pName)) { this.properties[pName].required = true; } } } } } function initProperty(parent, properties, propertyName) { properties[propertyName] = { "parent": parent, "name": propertyName, "type": "", "required": false, "fillProperty": function(pObj) { if(pObj.type == "object") { initClass(parent.innerClasses, this.name); parent.innerClasses[this.name].fillClass(pObj); this.type = capitalize(this.name); } else if(pObj.type == "array") { if(pObj.items.type == "object") { initClass(parent.innerClasses, this.name); parent.innerClasses[this.name].fillClass(pObj.items); this.type = "List<" + capitalize(this.name) + ">"; } else if(pObj.items.type === undefined && pObj.items["$ref"]) { var ref = pObj.items["$ref"].split("/"); this.type = "List<" + ref[ref.length -1] + ">"; } else if(pObj.items.enum) { initClass(parent.innerClasses, "Enum" + capitalize(this.name)); parent.innerClasses["Enum" + capitalize(this.name)].fillClass(pObj.items); this.type = "List<Enum" + capitalize(this.name) + ">"; } else { this.type = "List<" + parseDataType(pObj.items, "List ->" + this.name) + ">"; } } else if(pObj.type === undefined && pObj["$ref"]){ var ref = pObj["$ref"].split("/"); this.type = ref[ref.length -1]; } else { this.type = parseDataType(pObj, this.name); } } } } function parseDataType(pObj, pName) { var dataType switch(pObj.type) { case "string": { dataType = "String"; } break; case "integer": { dataType = "Int"; } break; case "number": { if(pObj.format == "double") { dataType = "Double"; } else { dataType = "Int"; } } break; case "boolean": { dataType = "Boolean"; } break; default: { dataType = "Any"; console.log(pName); } } if(dataType === undefined) console.log(pName); return dataType; }<file_sep>import capitalize from '../utils/capitalize.js' import fs from 'fs' export default function output2KtDataClass(ktClasses, outputFolder = "./output/", packageName = "default") { for(var ktClzz in ktClasses) { var content = "package " + packageName + "\n\n"; if(ktClasses[ktClzz].isEnum) { content += writeEnum(ktClasses[ktClzz]); } else { content += writeClass(ktClasses[ktClzz]); } fs.writeFile(outputFolder + ktClzz + ".kt", content, function(err) { if(err) console.error(err); }) } } function writeEnum(enumObj, numOfTabs = 0) { var tabs = "\t".repeat(numOfTabs); var content = tabs + "enum class " + capitalize(enumObj.name) + " {\n"; for(var i = 0; i < enumObj.values.length; i++) { content += "\n" + tabs + "\t" + enumObj.values[i] + "," } content = content.slice(0, -1); content += "\n" + tabs + "}\n"; return content; } function writeClass(classObj, numOfTabs = 0) { var tabs = "\t".repeat(numOfTabs); var content = tabs + "data class " + capitalize(classObj.name) + " (\n"; var properties = classObj.properties; content += writeProperties(properties, numOfTabs + 1); content += "\n" + tabs + ")"; if(classObj.innerClasses && Object.keys(classObj.innerClasses).length === 0 && classObj.innerClasses.constructor === Object) { return content; } content += "\n" + tabs + "{\n"; for(var inClzz in classObj.innerClasses) { if(classObj.innerClasses[inClzz].isEnum) { content += writeEnum(classObj.innerClasses[inClzz], numOfTabs + 1) + "\n"; } else { content += writeClass(classObj.innerClasses[inClzz], numOfTabs + 1) + "\n"; } } content = content.slice(0, -1); content += "\n" + tabs + "}\n"; return content; } function writeProperties(properties, numOfTabs = 0) { var content = ""; var tabs = "\t".repeat(numOfTabs); var nullablePart = "?"; for(var p in properties) { content += "\n" + tabs + "var " + properties[p].name + ": " + properties[p].type; if(!properties[p].required) content += nullablePart; content += ","; } content = content.slice(0, -1); return content; } <file_sep>import jsonfile from 'jsonfile' import parse2object from './processor/index.js' import output2KtDataClass from './file-output/index.js' const args = process.argv.slice(2); const inputFile = args[0]; const outputFolder = args[1]; const pack = args[2]; jsonfile.readFile(inputFile, function (err, obj) { var ktClasses = parse2object(obj); output2KtDataClass(ktClasses, outputFolder, pack); })
a218901675a188b47cb7ff11c9067a3f3dcfa8fe
[ "Markdown", "JavaScript" ]
4
Markdown
brunomurozaki/openapi2kt-dataclass
78e0a10a56deaf454b3461d687e982577588183b
9c162616b3dfdfb78748036eb17c7762f59c59a4
refs/heads/master
<file_sep>package com.akshay.employeeattendance.ui.EmployeeAttendanceActivity import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.akshay.employeeattendance.data.EmployeeRequest import com.akshay.employeeattendance.network.Repository.DataRepository class EmployeeAttendanceViewModelFactory ( private val requestData: EmployeeRequest, private val dataRepository: DataRepository ) : ViewModelProvider.NewInstanceFactory() { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { return EmployeeAttendanceViewModel(requestData, dataRepository) as T } }<file_sep>package com.akshay.employeeattendance.ui.EmployeeSelectionActivity import android.content.Intent import android.os.Bundle import android.util.Log import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.google.android.material.snackbar.Snackbar import com.akshay.employeeattendance.R import com.akshay.employeeattendance.internal.ScopeActivity import com.akshay.employeeattendance.network.Connectivity import com.akshay.employeeattendance.ui.EmployeeAttendanceActivity.EmployeeAttendanceActivity import kotlinx.android.synthetic.main.activity_main.* import kotlinx.coroutines.launch import org.kodein.di.KodeinAware import org.kodein.di.android.closestKodein import org.kodein.di.generic.instance import java.lang.NumberFormatException import java.lang.StringBuilder import java.text.SimpleDateFormat import java.util.* class MainActivity : ScopeActivity(), KodeinAware { override val kodein by closestKodein() private val mainActivityViewModelFactory : MainActivityViewModelFactory by instance() private lateinit var viewModel: MainActivityViewModel var employeeIdList : MutableList<Int> = mutableListOf<Int>() var employeeList: MutableList<String> = mutableListOf<String>() var yearList : MutableList<Int> = mutableListOf<Int>() var monthList : MutableList<String> = mutableListOf<String>() var selectedEmployeeName : String = "" var selectedEmployeeId : Int = 0 var selectedMonthIndex : Int = 99 var selectedMonth : String = "" var selectedYear : Int = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) viewModel = ViewModelProviders.of(this, mainActivityViewModelFactory).get(MainActivityViewModel::class.java) bindUI() createYearList() setYearDropDown() createMonthList() setMonthDropDown() viewAttendanceButton.setOnClickListener{ viewEmployeeAttendanceReport(it) } selectEmployeeDropDown.onFocusChangeListener = View.OnFocusChangeListener{ view, focused -> if(focused) { if(!Connectivity.isConnectedToInternet(this)) { val snackbar = Snackbar.make(view, getString(R.string.no_internet_connection), Snackbar.LENGTH_LONG) snackbar.show() } } } selectEmployeeDropDown.onItemClickListener = AdapterView.OnItemClickListener{ parent, view, position, id -> Log.e("E","Clicked") } selectEmployeeDropDown.setOnItemClickListener{ parent, view, position, id -> selectedEmployeeName = employeeList[position] selectedEmployeeId = employeeIdList[position] selectEmployeeDropDown.setError(null) } selectMonthDropDown.setOnItemClickListener{ parent, view, position, id -> selectedMonth = monthList[position] selectedMonthIndex = position selectMonthDropDown.setError(null) } selectYearDropDown.setOnItemClickListener{ parent, view, position, id -> selectedYear = yearList[position] selectYearDropDown.setError(null) } } private fun viewEmployeeAttendanceReport(view : View) { if(Connectivity.isConnectedToInternet(this)){ if(selectedEmployeeId == 0) { selectEmployeeDropDown.setError(getString(R.string.select_employee)) } if(selectedMonthIndex == 99) { selectMonthDropDown.setError(getString(R.string.select_month)) } if(selectedYear == 0) { selectYearDropDown.setError(getString(R.string.select_year)) } if(selectedEmployeeId != 0 && selectedMonthIndex != 99 && selectedYear!= 0) { var fromDate = formatDate(selectedYear, selectedMonthIndex, 1) var toDate = formatDate(selectedYear, selectedMonthIndex, 31) Log.e(""+fromDate," "+toDate) val intent = Intent(this@MainActivity, EmployeeAttendanceActivity::class.java) intent.putExtra(getString(R.string.emp_name),selectedEmployeeName) intent.putExtra(getString(R.string.emp_id),selectedEmployeeId) intent.putExtra(getString(R.string.from_date),fromDate) intent.putExtra(getString(R.string.to_date),toDate) intent.putExtra(getString(R.string.month), selectedMonth) intent.putExtra(getString(R.string.year),selectedYear) startActivity(intent) } } else{ val snackbar = Snackbar.make(view, getString(R.string.no_internet_connection), Snackbar.LENGTH_LONG) snackbar.setAction("RETRY") { viewEmployeeAttendanceReport(view) } snackbar.show() } } private fun formatDate(year: Int, month : Int, day: Int) : String { val builder = StringBuilder() builder.append(year.toString()).append("-").append((month+1).toString()).append("-").append(day).toString() return builder.toString() } private fun bindUI() = launch { val employees = viewModel.employees.await() employees.observe(this@MainActivity, Observer { if(it == null) return@Observer //Adding all employees fetched from API into MutableList for (item in it) { if(item.name!= null && item.emp_id != null && item.emp_id.toIntOrNull() != null) { try{ employeeIdList.add(item.emp_id.toInt()) } catch (e : NumberFormatException){ Log.e("NumberFormatException",""+e) } employeeList.add(item.name) } } setEmployeesDropDown() }) } fun setEmployeesDropDown() { val adapter = ArrayAdapter( this, R.layout.dropdown_menu_popup_item, employeeList ) selectEmployeeDropDown.setAdapter(adapter) } fun setYearDropDown() { val adapter = ArrayAdapter( this, R.layout.dropdown_menu_popup_item, yearList ) selectYearDropDown.setAdapter(adapter) } fun setMonthDropDown() { val adapter = ArrayAdapter( this, R.layout.dropdown_menu_popup_item, monthList ) selectMonthDropDown.setAdapter(adapter) } fun createYearList() { val c1 = Calendar.getInstance() c1.set(1995,1,1) val c2 = Calendar.getInstance() while(c1.compareTo(c2) < 1){ yearList.add(c1.get(Calendar.YEAR)) c1.add((Calendar.YEAR),1) } } fun createMonthList() { val formatd = SimpleDateFormat("MMMM") val c1 = Calendar.getInstance() c1.set(Calendar.MONTH,0) monthList.add(formatd.format(c1.time)) c1.add((Calendar.MONTH),1) while(c1.get(Calendar.MONTH) != 0){ monthList.add(formatd.format(c1.time)) c1.add((Calendar.MONTH),1) } } } <file_sep>package com.akshay.employeeattendance.ui.EmployeeAttendanceActivity import androidx.lifecycle.ViewModel import com.akshay.employeeattendance.data.EmployeeRequest import com.akshay.employeeattendance.internal.lazyDeferred import com.akshay.employeeattendance.network.Repository.DataRepository class EmployeeAttendanceViewModel (requestData : EmployeeRequest, dataRepository: DataRepository) : ViewModel(){ val employees by lazyDeferred { dataRepository.getEmployeeAttendance(requestData.empId, requestData.fromDate, requestData.toDate) } }<file_sep># EmployeeAttendance Android App to view the Employee Attendance Report<br /> You can download the APK from [here](https://github.com/DevAkshay/PXS2019-AkshayKumar/blob/master/app-debug.apk) ## Prerequisites - Andriod Studio v3.4 - Gradle v5.1.1 ## Checkout Clone the project by using the below git command or in Android studio start screen you get a option "Checkout project from Version control" there you can enter the above clone link ```bash git clone <EMAIL>:DevAkshay/PXS2019-AkshayKumar.git ``` ## Build and Run You can direcly run the app by clicking on the Run in android studio either in Emulator or usb debugging enabled android device ## Testing Select the Employee, Month and Year from the drop down and click on View Attendance Report button, you will the get the report of that employee for that month <file_sep>package com.akshay.employeeattendance.network.DataSource import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.akshay.employeeattendance.data.Employee import com.akshay.employeeattendance.data.EmployeeAttendance import com.akshay.employeeattendance.network.ApiService import java.io.IOException class EmployeeListDataSourceImpl(private val apiService: ApiService) : EmployeeListDataSource { private val _downloadedEmployeeList = MutableLiveData<List<Employee>>() private val _downloadedEmployeeAttendanceList = MutableLiveData<List<EmployeeAttendance>>() override val downloadedEmployeeList: LiveData<List<Employee>> get() = _downloadedEmployeeList override val downloadedEmployeeAttendanceList: LiveData<List<EmployeeAttendance>> get() = _downloadedEmployeeAttendanceList override suspend fun fetchEmployees() { try { val fetchEmployees = apiService.getEmployees().await() _downloadedEmployeeList.postValue(fetchEmployees) } catch (e: IOException) { Log.e("Connecting","No Internet") } } override suspend fun fetchEmployeeAttendance(employeeId : Int, fromDate : String, toDate : String) { try { val fetchEmployeeAttendance = apiService.getEmployeeAttendance(employeeId,fromDate,toDate).await() _downloadedEmployeeAttendanceList.postValue(fetchEmployeeAttendance) } catch (e: IOException) { Log.e("Connecting","No Internet") } } }<file_sep>package com.akshay.employeeattendance.network import android.util.Log import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory import com.akshay.employeeattendance.data.Employee import com.akshay.employeeattendance.data.EmployeeAttendance import com.akshay.employeeattendance.network.Interceptor.ConnectivityInterceptor import kotlinx.coroutines.Deferred import okhttp3.Interceptor import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.Field import retrofit2.http.FormUrlEncoded import retrofit2.http.GET import retrofit2.http.POST const val API_KEY = "e76c37b493ea168cea60b8902072387caf297979" interface ApiService { @GET("accounting/att_rprt_api.php?$API_KEY") fun getEmployees() : Deferred<List<Employee>> @FormUrlEncoded @POST("accounting/att_rprt_api.php?$API_KEY") fun getEmployeeAttendance(@Field("emp_id") EmpId: Int, @Field("from_dt") FromDt : String, @Field("to_dt") ToDt : String ) : Deferred<List<EmployeeAttendance>> companion object{ operator fun invoke(connectivityInterceptor: ConnectivityInterceptor): ApiService { val requestInterceptor = Interceptor { chain -> val url = chain.request() .url() .newBuilder() .build() val request = chain.request() .newBuilder() .url(url) .build() Log.e("URL ",""+request.url()); return@Interceptor chain.proceed(request) } val okHttpClient = OkHttpClient.Builder() .addInterceptor(requestInterceptor) .addInterceptor(connectivityInterceptor) .build() return Retrofit.Builder() .client(okHttpClient) .baseUrl("http://parxsys.com/") .addCallAdapterFactory(CoroutineCallAdapterFactory()) .addConverterFactory(GsonConverterFactory.create()) .build() .create(ApiService::class.java) } } }<file_sep>package com.akshay.employeeattendance.data data class EmployeeAttendance( val emp_id: String?, val entry_at: String?, val exit_at: String? ) <file_sep>package com.akshay.employeeattendance import android.app.Application import com.akshay.employeeattendance.data.EmployeeRequest import com.akshay.employeeattendance.network.* import com.akshay.employeeattendance.network.DataSource.EmployeeListDataSource import com.akshay.employeeattendance.network.DataSource.EmployeeListDataSourceImpl import com.akshay.employeeattendance.network.Interceptor.ConnectivityInterceptor import com.akshay.employeeattendance.network.Interceptor.ConnectivityInterceptorImpl import com.akshay.employeeattendance.network.Repository.DataRepository import com.akshay.employeeattendance.network.Repository.DataRepositoryImpl import com.akshay.employeeattendance.ui.EmployeeAttendanceActivity.EmployeeAttendanceViewModelFactory import com.akshay.employeeattendance.ui.EmployeeSelectionActivity.MainActivityViewModelFactory import org.kodein.di.Kodein import org.kodein.di.KodeinAware import org.kodein.di.android.androidModule import org.kodein.di.generic.* class AttendanceApplication : Application(), KodeinAware { override val kodein = Kodein.lazy { import(androidModule(this@AttendanceApplication)) bind<ConnectivityInterceptor>() with singleton { ConnectivityInterceptorImpl( instance() ) } bind() from singleton { ApiService(instance()) } bind<EmployeeListDataSource>() with singleton { EmployeeListDataSourceImpl( instance() ) } bind<DataRepository>() with singleton { DataRepositoryImpl( instance() ) } bind() from provider { MainActivityViewModelFactory( instance() ) } bind() from factory() { requestData : EmployeeRequest -> EmployeeAttendanceViewModelFactory( requestData, instance() ) } } }<file_sep>package com.akshay.employeeattendance.network.Repository import androidx.lifecycle.LiveData import com.akshay.employeeattendance.data.Employee import com.akshay.employeeattendance.data.EmployeeAttendance import com.akshay.employeeattendance.network.DataSource.EmployeeListDataSource class DataRepositoryImpl(private val employeeListDataSource: EmployeeListDataSource) : DataRepository { private var allEmployeeList : LiveData<List<Employee>> private var allEmployeeAttendanceList : LiveData<List<EmployeeAttendance>> init { allEmployeeList = employeeListDataSource.downloadedEmployeeList allEmployeeAttendanceList = employeeListDataSource.downloadedEmployeeAttendanceList } override suspend fun getEmployees(): LiveData<List<Employee>> { employeeListDataSource.fetchEmployees() return allEmployeeList } override suspend fun getEmployeeAttendance(employeeId : Int, fromDate : String, toDate : String): LiveData<List<EmployeeAttendance>> { employeeListDataSource.fetchEmployeeAttendance(employeeId, fromDate, toDate) return allEmployeeAttendanceList } }<file_sep>package com.akshay.employeeattendance.network.Repository import androidx.lifecycle.LiveData import com.akshay.employeeattendance.data.Employee import com.akshay.employeeattendance.data.EmployeeAttendance interface DataRepository { suspend fun getEmployees() : LiveData<List<Employee>> suspend fun getEmployeeAttendance(employeeId : Int, fromDate : String, toDate : String): LiveData<List<EmployeeAttendance>> }<file_sep>package com.akshay.employeeattendance.data data class Employee( val emp_id: String?, val name: String? )<file_sep>package com.akshay.employeeattendance.ui.EmployeeAttendanceActivity import android.graphics.Color import android.os.Build import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.widget.TableRow import android.widget.TextView import android.widget.Toast import androidx.core.content.res.ResourcesCompat import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.akshay.employeeattendance.R import com.akshay.employeeattendance.internal.ScopeActivity import com.akshay.employeeattendance.data.EmployeeRequest import kotlinx.android.synthetic.main.activity_employee_attendance.* import kotlinx.android.synthetic.main.activity_employee_attendance.toolbar import kotlinx.coroutines.launch import org.kodein.di.KodeinAware import org.kodein.di.android.closestKodein import org.kodein.di.generic.factory import java.lang.StringBuilder import java.math.RoundingMode import java.text.SimpleDateFormat import java.time.YearMonth import java.util.* class EmployeeAttendanceActivity : ScopeActivity(), KodeinAware { override val kodein by closestKodein() private val employeeAttendanceViewModelFactory : ((EmployeeRequest) -> EmployeeAttendanceViewModelFactory) by factory() private lateinit var viewModel: EmployeeAttendanceViewModel val attendanceList : MutableMap<Int, Double> = mutableMapOf<Int,Double>() var fromDate : String = "" var month : String = "" var toDate : String = "" var empId : Int = 0 var empName : String = "" var year : Int = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_employee_attendance) setSupportActionBar(toolbar) //Intents from previous activity empName = intent.getStringExtra(getString(R.string.emp_name)) empId = intent.getIntExtra(getString(R.string.emp_id),0) fromDate = intent.getStringExtra(getString(R.string.from_date)) toDate = intent.getStringExtra(getString(R.string.to_date)) month = intent.getStringExtra(getString(R.string.month)) year = intent.getIntExtra(getString(R.string.year),0) viewModel = ViewModelProviders. of(this, employeeAttendanceViewModelFactory(EmployeeRequest(empId,fromDate,toDate))) .get(EmployeeAttendanceViewModel::class.java) bindUI() } override fun onSupportNavigateUp(): Boolean { onBackPressed() return true } private fun bindUI() = launch { val employees = viewModel.employees.await() employees.observe(this@EmployeeAttendanceActivity, Observer { if(it == null) return@Observer if(it.isEmpty()) { Toast.makeText(applicationContext,getString(R.string.no_data_found), Toast.LENGTH_LONG).show() } for (data in it) { //Calculating difference of each day entry and storing it in map val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") val entryAt = dateFormat.parse(data.entry_at) val exitAt = dateFormat.parse(data.exit_at) val diffInMin = (exitAt.time - entryAt.time)/(60*60*1000).toDouble() val diffInHours = diffInMin.toBigDecimal().setScale(1, RoundingMode.HALF_DOWN).toDouble() val dayFormat = SimpleDateFormat("dd") val day = dayFormat.format(entryAt.time).toInt() if(attendanceList.containsKey(day)) { attendanceList[day] = attendanceList[day]!!.plus(diffInHours) } else { attendanceList.put(day, diffInHours) } } enableUIs() setHeader() CreateReportTable() createFinalReport() }) } fun enableUIs() { progressBar.visibility = View.GONE cardAttendanceReport.visibility = View.VISIBLE cardFinalReport.visibility = View.VISIBLE } fun setHeader() { val builder = StringBuilder() builder.append(empName).append("'s ").append(getString(R.string.attendance_report_of)).append(" ").append(month).append(" ").append(year) headerText.text = builder.toString() } fun CreateReportTable() { val rowHead = LayoutInflater.from(this).inflate(R.layout.row_item, null) as TableRow val coloumheader1 = (rowHead.findViewById<View>(R.id.attrib_name) as TextView) coloumheader1.text=(getString(R.string.date_of_the_month)) coloumheader1.setTextColor(Color.parseColor("#000000")) coloumheader1.setTypeface(ResourcesCompat.getFont(this,R.font.roboto_medium)) //coloumheader1.setTypeface(Typeface.DEFAULT_BOLD) val coloumnheader2 = (rowHead.findViewById<View>(R.id.attrib_value) as TextView) coloumnheader2.text=(getString(R.string.no_of_hours_logged)) coloumnheader2.setTextColor(Color.parseColor("#000000")) coloumnheader2.setTypeface(ResourcesCompat.getFont(this,R.font.roboto_medium)) //coloumnheader2.setTypeface(Typeface.DEFAULT_BOLD) attendanceReportTable!!.addView(rowHead) var i = 0 for ((mKey, mValue) in attendanceList) { val row = LayoutInflater.from(this).inflate(R.layout.row_item, null) as TableRow val coloum1 = (row.findViewById<View>(R.id.attrib_name) as TextView) coloum1.text=mKey.toString() val coloum2 = (row.findViewById<View>(R.id.attrib_value) as TextView) val hours : Double = mValue/60 coloum2.text= mValue.toString()//hours.toBigDecimal().setScale(1, RoundingMode.UP).toDouble().toString() if(i%2 == 0) { coloum1.setBackgroundColor(Color.parseColor("#f2f2f2")) coloum2.setBackgroundColor(Color.parseColor("#f2f2f2")) } attendanceReportTable!!.addView(row) i += 1 } attendanceReportTable!!.requestLayout() } fun createFinalReport() { var daysInMonth : Int var totalLoggedMinutes : Double = 0.0 val dateFormat = SimpleDateFormat("yyyy-MM-dd") val yearFormat = SimpleDateFormat("yyyy") val monthFormat = SimpleDateFormat("MM") val date = dateFormat.parse(fromDate) val year = yearFormat.format(date).toInt() val month = monthFormat.format(date).toInt() if(Build.VERSION.SDK_INT >= 26) { daysInMonth = YearMonth.of(year, month).lengthOfMonth() } else { val gregorianCalendar = GregorianCalendar(year,month, 1) daysInMonth = gregorianCalendar.getActualMaximum(Calendar.DAY_OF_MONTH) } for((k,v) in attendanceList) { totalLoggedMinutes += v } hoursLoggedText.text = totalLoggedMinutes.toString() daysPresentText.text = attendanceList.size.toString() daysAbsent.text = (daysInMonth - attendanceList.size).toString() } } <file_sep>package com.akshay.employeeattendance.data data class EmployeeRequest( val empId: Int, val fromDate: String, val toDate: String )<file_sep>package com.akshay.employeeattendance.network import android.content.Context import android.net.ConnectivityManager @Suppress("DEPRECATION") class Connectivity { companion object Connection{ fun isConnectedToInternet(context: Context) : Boolean { val connectivityManager = context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val networkInfo = connectivityManager.activeNetworkInfo return networkInfo != null && networkInfo.isConnected } } }<file_sep>package com.akshay.employeeattendance.network.Interceptor import okhttp3.Interceptor interface ConnectivityInterceptor : Interceptor { }<file_sep>package com.akshay.employeeattendance.network.DataSource import androidx.lifecycle.LiveData import com.akshay.employeeattendance.data.Employee import com.akshay.employeeattendance.data.EmployeeAttendance interface EmployeeListDataSource { val downloadedEmployeeList : LiveData<List<Employee>> val downloadedEmployeeAttendanceList : LiveData<List<EmployeeAttendance>> suspend fun fetchEmployees() suspend fun fetchEmployeeAttendance(employeeId : Int, fromDate : String, toDate : String) }<file_sep>package com.akshay.employeeattendance.ui.EmployeeSelectionActivity import androidx.lifecycle.ViewModel import com.akshay.employeeattendance.internal.lazyDeferred import com.akshay.employeeattendance.network.Repository.DataRepository class MainActivityViewModel (dataRepository: DataRepository) : ViewModel(){ val employees by lazyDeferred { dataRepository.getEmployees() } }<file_sep>package com.akshay.employeeattendance.network.Interceptor import android.content.Context import com.akshay.employeeattendance.network.Connectivity import okhttp3.Interceptor import okhttp3.Response import java.io.IOException class ConnectivityInterceptorImpl(context : Context) : ConnectivityInterceptor { private val appContext = context.applicationContext override fun intercept(chain: Interceptor.Chain): Response { if(!Connectivity.isConnectedToInternet(appContext)) throw IOException() return chain.proceed(chain.request()) } }
7c889351dd0d5a9ec3025d19158bac1807b4709a
[ "Markdown", "Kotlin" ]
18
Kotlin
DevAkshay/PXS2019-AkshayKumar
ba23df4daaec82a8d3b01e82111aa4f4ae1b6a78
ae31ba730c3d89001a4b3e196b832ecdbc918f9c
refs/heads/master
<repo_name>wasabi-io/ts-react-project-skeleton<file_sep>/tools/dev/webpack.js process.env.NODE_ENV = "development"; const webpack = require("webpack"); const CopyWebpackPlugin = require("copy-webpack-plugin"); var WebpackNotifierPlugin = require("webpack-notifier"); const configureWebpack = require("../common/webpack"); const aliases = require("../aliases.json"); const entries = require("../entries.json"); const paths = require("../paths.json"); const settings = new configureWebpack({ server: true, loader: { ts: { configFileName: "tsconfig.json" }, css: true, url: true, file: true }, paths: paths, entries: entries, aliases: aliases }); settings.webpack.output = { filename: "bundle.js" }; settings.webpack.plugins = [ new WebpackNotifierPlugin({ alwaysNotify: true }), new webpack.HotModuleReplacementPlugin(), new CopyWebpackPlugin([{ from: settings.paths.assets, to: "./" }, { from: "../node_modules/bootstrap/dist", to: "./vendor/bootstrap" } ]) ]; module.exports = settings.webpack; <file_sep>/tools/dev/tsconfig.json { "compilerOptions": { "baseUrl": "../../", "rootDirs": [ "./site", "./src" ], "paths": { "wasabi-ui/lib/*": [ "./src/*" ], "wasabi-ui": [ "./src/index" ], "wasabi-core/lib/*": [ "./packages/core/src/*" ], "wasabi-core": [ "./packages/core/src/index" ], "wasabi-view-api/lib/*": [ "./packages/view-api/src/*" ], "wasabi-view-api": [ "./packages/view-api/src/index" ], "wasabi-view/lib/*": [ "./packages/view/src/*" ], "wasabi-view": [ "./packages/view/src/index" ] }, "target": "es5", "module": "commonjs", "declaration": false, "noImplicitAny": false, "preserveConstEnums": true, "sourceMap": true, "moduleResolution": "node", "emitDecoratorMetadata": true, "experimentalDecorators": true, "removeComments": false, "jsx": "react", "outDir": "./lib" } }<file_sep>/README.md ## ts-react-project-skeleton #### Motivation #### Getting Started * Before Start Project ```ssh $ git clone ....` $ cd ts-react-project-skeleton $ npm install ``` * run start (Development Mode) ```ssh $ npm start ``` * run test (Test Mode) ```ssh $ npm test ``` * build project (Production Mode) ```ssh $ npm start ``` * run coverage ```ssh $ npm run coverage ``` * generate api docs ```ssh $ npm run docs ``` * build library as javascript (common-js) ```ssh $ npm build ``` <file_sep>/tools/util/Objects.js const Objects = function Objects(){ const me = this; me.merge = function(src, destination) { if(!src) { return destination || {}; } else { destination = destination || {}; } for(var key in src) { if(Object.prototype.hasOwnProperty.call(src, key)) { dest[key] = src[key]; } } return dest; } }; module.exports = new Objects(); <file_sep>/tools/test/helper.js const resolver = require("wasabi-common/lib/util/Resolver"); resolver.addModule("src");<file_sep>/src/util/Compare.ts import * as shallowCompare from "react-addons-shallow-compare"; let compare: any = shallowCompare; if(compare.default) { compare = compare.default; } export default compare; <file_sep>/src/util/index.ts export { default as Compare } from "./Compare";<file_sep>/CHANGELOG.md ## CHANGE LOG<file_sep>/src/component/Component.ts import {Class, Functions, Generator, Types} from "wasabi-common"; import * as React from "react"; import Compare from "../util/Compare"; export interface Props { children?: any } export interface State { } /** * Base component which wraps render function in a try catch structure * Any child components who extends from this component will get protection when * Exception thrown, so protect component life cycle. */ abstract class Component <P extends Props, S extends State> extends React.Component <any, any> { refs: { [key: string]: any }; props: P; state: S; /** * * @type {string} */ protected componentId: string = Generator.guid(); /** * * @param props * @param context */ protected constructor(props?: P, context?: any) { super(props, context); Class.bindAll(this); } getComponentId(){ return this.componentId; } /** * Decides ant update is necessary for re-rendering. * Compares old props and state objects with the newer ones without going deep. * @param {Object} nextProps * @param {Object} nextState * @returns {boolean} "true" component shoud update ,"false" otherwise. */ public shouldComponentUpdate(nextProps: Object, nextState: Object): boolean { return Compare(this, nextProps, nextState); } /** * Returns class name of the component. * @return {string} name. */ public getName (): string { return Functions.getName(this.constructor); } /** * * @return {JSX.Element} */ public render(): JSX.Element { return this.props.children; } /** * * @return {State} */ public cloneState(): any { return Types.getClone(this.state); } } export default Component;
41861ba6d1a051854b7b92833587860e488c9526
[ "JavaScript", "TypeScript", "JSON with Comments", "Markdown" ]
9
JavaScript
wasabi-io/ts-react-project-skeleton
147bce5127e38dc44e645cb79af4662dc838d320
3c17c1607fc06f8d567403882b051efd970241b8
refs/heads/master
<repo_name>FletcherFT/RL<file_sep>/Asgeir_DDPG/Actor_network.py import tensorflow as tf import numpy as np from tensorflow.python.ops.nn import relu, tanh class Actor: """ Actor Neural Network model. """ def __init__(self, action_shape, action_bound, observation_shape, scope, session, batch_size, params): with tf.variable_scope(scope): self.scope = scope self.num_actions = action_shape[0] self.action_bound = action_bound self.num_observations = observation_shape[0] self.lr = params['a_lr'] self.hidden_layers = params['a_hl'] self.batch_size = batch_size self.session = session self.create_model() def add_placeholders(self): input_pl = tf.placeholder(tf.float32, shape=(None, self.num_observations)) action_gradient_pl = tf.placeholder(tf.float32, shape=(None, self.num_actions)) return input_pl, action_gradient_pl def nn(self, obs): for i in range(len(self.hidden_layers)): if i == 0: net = tf.layers.dense(inputs = obs, units = self.hidden_layers[i], activation = relu, name = 'ActorLayer' + str(1+i)) else: net = tf.layers.dense(inputs = net, units = self.hidden_layers[i], activation = relu, name = 'ActorLayer' + str(1+i)) out = tf.layers.dense(inputs=net, units=self.num_actions, activation=tanh, name='ActorOutputLayer') scaled_out = tf.multiply(out, self.action_bound) self.trainables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=self.scope) return out, scaled_out def create_model(self): self.input_pl, self.action_gradient_pl = self.add_placeholders() out, scaled_out = self.nn(self.input_pl) self.scaled_action = scaled_out self.unnormalized_actor_gradients = tf.gradients(self.scaled_action, self.trainables, -self.action_gradient_pl) self.actor_gradients = tf.tuple(list(map(lambda x: tf.div(x, self.batch_size), self.unnormalized_actor_gradients))) optimizer = tf.train.AdamOptimizer(learning_rate = self.lr) self.train_op = optimizer.apply_gradients(zip(self.actor_gradients, self.trainables)) def assign_trainables(self, ts, tau=1.0): ops = [] for i, t in enumerate(self.trainables): ops.append(t.assign((1-tau) * t.value() + tau * ts[i].value())) return ops def train_step(self, observations, a_gradient): _, scaled_out = self.session.run( [self.train_op, self.scaled_action], feed_dict = {self.input_pl: observations, self.action_gradient_pl: a_gradient}) def predict(self, observation): scaled_out = self.session.run( self.scaled_action, feed_dict = {self.input_pl: observation}) return scaled_out def get_actor_gradient(self, observations, action_gradient): actor_gradients = self.session.run( self.actor_gradients, feed_dict = {self.input_pl: observations, self.action_gradient_pl: action_gradient}) return actor_gradients def get_un_actor_gradient(self, observations, action_gradient): actor_gradients = self.session.run( self.unnormalized_actor_gradients, feed_dict = {self.input_pl: observations, self.action_gradient_pl: action_gradient}) return actor_gradients<file_sep>/Fletcher_PPO/AUVSim-v0/Dec-08_17-46-31/fakegym.py import rospy import dynamic_reconfigure.client from sensor_msgs.msg import JointState from nav_msgs.msg import Odometry from gazebo_msgs.msg import ModelState from std_srvs.srv import Empty import tf.transformations as transform import random from math import pi from gym import spaces from gym.envs.registration import EnvSpec import numpy as np class env(): def __init__(self,discrete=False,steplimit=1000): self.state = None self.scale = 30.0 self.nh = rospy.init_node('fakegyminterface') self.steps = 0 self.steplimit = steplimit if discrete: self.action_space = spaces.Discrete(6) else: self.action_space = spaces.Box(low=-1, high=1, shape=(6,)) self.observation_space = spaces.Box(low=-100, high=100, shape=(12,)) self.spec = EnvSpec('AUVSim-v0',timestep_limit=self.steplimit) self.rng = random self.lastaction = [0.0,0.0,0.0,0.0,0.0,0.0] try: #Subscriber to get the model's pose & twist rospy.Subscriber('/brov/state', Odometry, self.updateState) #Publisher to set randomize the model pose & twist on each restart self.reset_pub = rospy.Publisher('/gazebo/set_model_state', ModelState, queue_size=1) self.thrust_pub = rospy.Publisher('/brov/thruster_command', JointState, queue_size=1) self.step_srv = rospy.ServiceProxy('/gazebo/step', Empty) rospy.wait_for_service('/gazebo/step') self.step_srv() except rospy.ROSInterruptException: pass def updateState(self,newState): x = newState.pose.pose.position.x y = newState.pose.pose.position.y z = newState.pose.pose.position.z quat = ( newState.pose.pose.orientation.x, newState.pose.pose.orientation.y, newState.pose.pose.orientation.z, newState.pose.pose.orientation.w,) euler = transform.euler_from_quaternion(quat) u = newState.twist.twist.linear.x v = newState.twist.twist.linear.y w = newState.twist.twist.linear.z p = newState.twist.twist.angular.x q = newState.twist.twist.angular.y r = newState.twist.twist.angular.z self.state = (x,y,z,euler[0],euler[1],euler[2],u,v,w,p,q,r,) def reset(self): #Message to send to the simulator zeroState = ModelState() zeroState.model_name = 'brov' zeroState.pose.position.x = self.rng.uniform(-100.0,100.0) zeroState.pose.position.y = self.rng.uniform(-100.0,100) zeroState.pose.position.z = self.rng.uniform(-200.0,0.0) r = self.rng.uniform(-pi,pi) p = self.rng.uniform(-pi,pi) y = self.rng.uniform(-pi,pi) quat = transform.quaternion_from_euler(r,p,y) zeroState.pose.orientation.x = quat[0] zeroState.pose.orientation.y = quat[1] zeroState.pose.orientation.z = quat[2] zeroState.pose.orientation.w = quat[3] zeroState.twist.linear.x = self.rng.uniform(-0.5,0.5) zeroState.twist.linear.y = self.rng.uniform(-0.5,0.5) zeroState.twist.linear.z = self.rng.uniform(-0.5,0.5) zeroState.twist.angular.x = self.rng.uniform(-0.1,0.1) zeroState.twist.angular.y = self.rng.uniform(-0.1,0.1) zeroState.twist.angular.z = self.rng.uniform(-0.1,0.1) #Send to the simulator self.reset_pub.publish(zeroState) #restart the step counter self.steps=0 state = [] state.append(zeroState.pose.position.x) state.append(zeroState.pose.position.y) state.append(zeroState.pose.position.z) state.append(r) state.append(p) state.append(y) state.append(zeroState.twist.linear.x ) state.append(zeroState.twist.linear.y ) state.append(zeroState.twist.linear.z ) state.append(zeroState.twist.angular.x) state.append(zeroState.twist.angular.y) state.append(zeroState.twist.angular.z) self.state = state return np.array(state) def step(self,action): thruster_msg = JointState() thruster_msg.name = ['thr1','thr2','thr3','thr4','thr5','thr6'] scaledaction = [self.scale*i for i in action] thruster_msg.position = [scaledaction[0],scaledaction[1],scaledaction[2],scaledaction[3], scaledaction[4],scaledaction[5]] self.lastaction = [scaledaction[0],scaledaction[1],scaledaction[2],scaledaction[3], scaledaction[4],scaledaction[5]] self.thrust_pub.publish(thruster_msg) rospy.wait_for_service('/gazebo/step') self.step_srv() self.steps+=1 done = self.steps>self.steplimit# or (abs(self.state[3]-0.0)<1e-2 and abs(self.state[9])<1e-2) return np.array(self.state), self.reward(), done, "don't look here" def reward(self): rollerr = abs(self.state[3]-0.0) pitcherr = abs(self.state[4]-0.0) #pitcherr = 0 #yawerr = abs(self.state[5]-0.0) yawerr = 0 RotationObj = 1.0/(rollerr+pitcherr+yawerr+1e-2) #EnergyObj = 1.0/(np.array(self.lastaction).sum()+1e-2) EnergyObj = 0.0 return RotationObj+EnergyObj def seed(self,i): self.rng.seed(i) def close(self): pass<file_sep>/Asgeir_DDPG/ReadMe.txt Instructions to utilize DDPG: 1. Copy the files and folders to a location of yoru choosing. 2. parameters.py contains variables that control network parameters, learning parameters, and so on. These may be changed by you. 3. Run ddpg_agent.py to begin training using your chosen parameters. 4. DDPG_OpenAI.ipynb is a notebook file that presents the main results from each Open AI Gym problem. The chosen environment is simulated by a previously trained network to demonstrate its performance. <file_sep>/Asgeir_DDPG/Critic_network.py import tensorflow as tf import numpy as np from tensorflow.python.ops.nn import relu, tanh class Critic: """ Critic Neural Network model. """ def __init__(self, action_shape, observation_shape, scope, session, params): with tf.variable_scope(scope): self.scope = scope self.num_actions = action_shape[0] self.num_observations = observation_shape[0] self.lr = params['c_lr'] self.hidden_layers = params['c_hl'] self.session = session self.create_model() def add_placeholders(self): input_pl = tf.placeholder(tf.float32, shape=(None, self.num_observations)) actions_pl = tf.placeholder(tf.float32, shape=(None, self.num_actions)) labels_pl = tf.placeholder(tf.float32, shape=(None, 1)) return input_pl, actions_pl, labels_pl def nn(self, obs, act): for i in range(len(self.hidden_layers)): if i == 0: net = tf.layers.dense(inputs = obs, units = self.hidden_layers[i], activation = relu, name = 'CriticLayer' + str(1+i)) elif i == 1: net = tf.concat([net, act], 1) # input actions at second hidden layer net = tf.layers.dense(inputs = net, units = self.hidden_layers[i], activation = relu, name = 'CriticLayer' + str(1+i)) else: net = tf.layers.dense(inputs = net, units = self.hidden_layers[i], activation = relu, name = 'CriticLayer' + str(1+i)) out = tf.layers.dense(inputs = net, units = 1, activation = None, name = 'CriticLayerOut') self.trainables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=self.scope) return out def create_model(self): self.input_pl, self.actions_pl, self.labels_pl = self.add_placeholders() self.q_vals = self.nn(self.input_pl, self.actions_pl) self.network_params = tf.trainable_variables() self.loss = tf.reduce_mean(tf.square(self.labels_pl - self.q_vals)) self.grads = tf.gradients(self.loss, self.trainables) optimizer = tf.train.AdamOptimizer(learning_rate = self.lr) self.train_op = optimizer.minimize(self.loss) self.action_gradient = tf.gradients(self.q_vals, self.actions_pl) def assign_trainables(self, ts, tau=1.0): ops = [] for i, t in enumerate(self.trainables): ops.append(t.assign((1-tau) * t.value() + tau * ts[i].value())) return ops def train_step(self, observations, labels, actions): loss, _, q_values = self.session.run( [self.loss, self.train_op, self.q_vals], feed_dict = {self.input_pl: observations, self.actions_pl: actions, self.labels_pl: labels}) return loss def predict(self, observation, action): q_values = self.session.run( self.q_vals, feed_dict = {self.input_pl: observation, self.actions_pl: action}) return q_values def get_action_gradient(self, observation, action): action_gradient = self.session.run( self.action_gradient, feed_dict = {self.input_pl: observation, self.actions_pl: action}) return action_gradient def get_gradients(self, observation, labels, action): grads = self.session.run( self.grads, feed_dict = {self.input_pl: observation, self.actions_pl: action, self.labels_pl: labels}) return grads def get_loss(self, observations, labels, actions): loss = self.session.run( self.loss, feed_dict = {self.input_pl: observations, self.actions_pl: actions, self.labels_pl: labels}) return loss <file_sep>/Asgeir_DDPG/load.py import gym from parameters import parse_args from ddpg import DDPG import matplotlib.pyplot as plt import tensorflow as tf import pickle import time import numpy as np def run_load(): agent_params, dppg_params, cnn_params, a_params, c_params = parse_args() env = gym.make(agent_params['environment']) action_frames = agent_params['action_frames'] steps = agent_params['steps'] if steps > env.spec.timestep_limit: steps = env.spec.timestep_limit action_shape = env.action_space.shape action_bound = env.action_space.high observation_shape = env.observation_space.shape tf.reset_default_graph() actions = [] with tf.Session() as session: ddpg = DDPG(action_shape, action_bound, observation_shape, dppg_params, cnn_params, a_params, c_params, session) saver = tf.train.Saver() ddpg.load(saver, agent_params['environment']) env.seed(300) reward_sum_v = 0 observation = env.reset() frames = action_frames for i in range(300): env.render() if frames == action_frames: action = ddpg.select_action([observation], stochastic = False, target = False, step = i)[0] if i > 100: action += 0.6 frames = 0 observation, reward, done, _ = env.step(action) actions.append(action) frames += 1 if frames == action_frames: reward_sum_v += reward if done: if frames != action_frames: reward_sum_v += reward # break plt.figure(figsize=(10,9)) plt.plot(actions, label='Action') plt.xlabel('Timestep'); plt.ylabel('Action') plt.xlim((0, len(actions))) plt.legend(loc=1); plt.grid() with open("Trainings/" + agent_params['environment'] + "/" + time.strftime("%d%m%Y") + "/statistics.txt", "rb") as fp: # Unpickling statistics = pickle.load(fp) statistics = np.array(statistics).T mean_training_rewards = statistics[0] mean_validation_rewards = statistics[1] C_losses = statistics[2] C_diffs = statistics[3] A_diffs = statistics[4] plt.figure(figsize=(10,9)) plt.subplot(221) plt.plot(C_losses, label='C loss') plt.xlabel('Episode'); plt.ylabel('loss') plt.xlim((0, len(C_losses))) plt.legend(loc=1); plt.grid() plt.subplot(222) plt.plot(C_diffs, label='C diff') plt.xlabel('Episode'); plt.ylabel('Difference') plt.xlim((0, len(C_diffs))) plt.legend(loc=1); plt.grid() plt.subplot(223) plt.plot(A_diffs, label='A diff') plt.xlabel('Episode'); plt.ylabel('Difference') plt.xlim((0, len(A_diffs))) plt.legend(loc=1); plt.grid() plt.subplot(224) plt.plot(mean_training_rewards, label='Mean training reward') plt.plot(mean_validation_rewards, label='Mean validation reward') plt.xlabel('Episode'); plt.ylabel('Mean reward') plt.xlim((0, len(mean_validation_rewards))) plt.legend(loc=4); plt.grid() plt.tight_layout(); plt.show() print(reward_sum_v) f = plt.figure() plt.plot(mean_training_rewards, label='Mean training reward') plt.plot(mean_validation_rewards, 'g', label='Mean validation reward') plt.xlabel('Episode', size=16); plt.ylabel('Mean reward', size=16) plt.xlim((0, len(mean_validation_rewards))) plt.legend(loc=4,prop={'size':12}); plt.tick_params(labelsize=14) plt.tight_layout(); plt.show() f.savefig("Trainings/" + agent_params['environment'] + "/" + time.strftime("%d%m%Y") + "rewards.pdf", bbox_inches='tight') env.render(close=True) if __name__ == '__main__': run_load()<file_sep>/Asgeir_DDPG/parameters.py # Agent parameters DEFAULT_EPISODES = 300 DEFAULT_STEPS = 1000 DEFAULT_ENVIRONMENT = 'Pendulum-v0' DEFAULT_ACTION_FRAMES = 1 DEFAULT_LOAD = False # DDPG learning parameters DEFAULT_MEMORY_CAPACITY = 100000 DEFAULT_GAMMA = 0.99 DEFAULT_MINI_BATCH_SIZE = 64 DEFAULT_TAU = 0.001 # Neural network parameters DEFAULT_LEARNING_RATE = 0.0001 # Actor network parameters DEFAULT_ACTOR_LEARNING_RATE = 0.0001 DEFAULT_ACTOR_HIDDEN_LAYERS = [200, 100] # Critic network parameters DEFAULT_CRITIC_LEARNING_RATE = 0.001 DEFAULT_CRITIC_HIDDEN_LAYERS = [200, 100] DEFAULT_ID = 0 def parse_args(): agent_params = {'episodes': DEFAULT_EPISODES, 'steps': DEFAULT_STEPS, 'environment': DEFAULT_ENVIRONMENT, 'action_frames' : DEFAULT_ACTION_FRAMES, 'load' : DEFAULT_LOAD} ddpg_params = {'memory_capacity': DEFAULT_MEMORY_CAPACITY, 'gamma': DEFAULT_GAMMA, 'mini_batch_size': DEFAULT_MINI_BATCH_SIZE, 'tau' : DEFAULT_TAU} cnn_params = {'lr': DEFAULT_LEARNING_RATE, 'mini_batch_size': DEFAULT_MINI_BATCH_SIZE} a_params = {'a_lr': DEFAULT_ACTOR_LEARNING_RATE, 'a_hl': DEFAULT_ACTOR_HIDDEN_LAYERS} c_params = {'c_lr':DEFAULT_CRITIC_LEARNING_RATE, 'c_hl': DEFAULT_CRITIC_HIDDEN_LAYERS} assert len(a_params['a_hl']) > 1 and len(c_params['c_hl']) > 1 return agent_params, ddpg_params, cnn_params, a_params, c_params<file_sep>/Asgeir_DDPG/ddpg.py import numpy as np import random as random import math import tensorflow as tf import pickle import time from collections import deque from Actor_network import Actor from Critic_network import Critic import Noise as N class DDPG: def __init__(self, action_shape, action_bound, observation_shape, ddpg_params, cnn_params, a_params, c_params, session): self.session = session self.gamma = ddpg_params['gamma'] self.mini_batch_size = ddpg_params['mini_batch_size'] self.tau = ddpg_params['tau'] self.memory = deque(maxlen=ddpg_params['memory_capacity']) self.action_shape = action_shape self.actor_noise = N.OrnsteinUhlenbeckActionNoise(mu=np.zeros(self.action_shape[0])) # initialize networks self.A = Actor(action_shape, action_bound, observation_shape, 'Actor_main', self.session, self.mini_batch_size, a_params) self.A_t = Actor(action_shape, action_bound, observation_shape, 'Actor_target', self.session, self.mini_batch_size, a_params) self.A_copy_target = self.A_t.assign_trainables(self.A.trainables, tau = 1.0) self.A_upda_target = self.A_t.assign_trainables(self.A.trainables, self.tau) self.C = Critic(action_shape, observation_shape, 'Critic_main', self.session, c_params) self.C_t = Critic(action_shape, observation_shape, 'Critic_target', self.session, c_params) self.C_copy_target = self.C_t.assign_trainables(self.C.trainables, tau = 1.0) self.C_upda_target = self.C_t.assign_trainables(self.C.trainables, self.tau) print ("Networks initialized") def select_action(self, obs, stochastic = False, target = False, step = 0): """ Selects the next action to take based on the current state and learned policy. Args: observation: the current state """ if target: action = self.A_t.predict(obs) else: action = self.A.predict(obs) if stochastic: nn = self.actor_noise() action += nn return action def update_state(self, observation, action, new_observation, reward, done): transition = {'observation': observation, 'action': action, 'new_observation': new_observation, 'reward': reward, 'is_done': done} self.memory.append(transition) def get_random_mini_batch(self): """ Gets a random, unique sample of transitions from the replay memory. """ rand_idxs = random.sample(range(len(self.memory)), self.mini_batch_size) mini_batch = [] for idx in rand_idxs: mini_batch.append(self.memory[idx]) return mini_batch def train_step(self): """ Updates the actor and critic networks based on the mini batch """ C_loss, C_difference, A_difference = 0, 0, 0 if len(self.memory) > self.mini_batch_size: mini_batch = self.get_random_mini_batch() # Calculations for critic network observations, new_observations, actions, C_labels, is_done = [], [], [], [], [] for sample in mini_batch: observations.append(sample['observation']) new_observations.append(sample['new_observation']) actions.append(sample['action']) C_labels.append(sample['reward']) is_done.append(sample['is_done']) new_actions = self.select_action(new_observations, stochastic = False, target = True) c_new_values = self.C_t.predict(new_observations, new_actions) for i in range(len(c_new_values)): # Latter is necissary to convert to array with dtybe of float 32 C_labels[i] = C_labels[i] + self.gamma * c_new_values[i] if not is_done[i] else C_labels[i] + 0 * c_new_values[i] # Convert appended calculations into an array observations = np.array(observations) actions = np.array(actions) C_labels = np.array(C_labels) # Train critic network C_loss = self.C.train_step(observations, C_labels, actions) # Calculations for actor network acts = self.select_action(observations, stochastic = False, target = True) action_gradients = self.C.get_action_gradient(observations, acts)[0] grad = self.A.get_actor_gradient(observations, np.array(action_gradients)) action_gradients = np.array(action_gradients) grad = np.array(grad) # Train actor network self.A.train_step(observations, action_gradients) # Slow update the target networks self.session.run(self.C_upda_target) self.session.run(self.A_upda_target) # Compute difference between main and target networks C_pred = self.C.predict(observations, actions) C_t_pred = self.C_t.predict(observations, actions) C_difference = np.mean((C_pred - C_t_pred)**2) A_pred = self.select_action(new_observations, stochastic = False, target = False) A_t_pred = self.select_action(new_observations, stochastic = False, target = True) A_difference = np.mean((A_pred - A_t_pred)**2) return C_loss, C_difference, A_difference def save(self, saver, env): try: saver.save(self.session, "Trainings/" + env + "/" + time.strftime("%d%m%Y") + "/model.ckpt") with open("Trainings/" + env + "/" + time.strftime("%d%m%Y") + "/memory.txt", "wb") as fp: pickle.dump(self.memory, fp) # Pickling print ("Networks saved") except Exception: print ("Could not save!") def load(self, saver, env, date = None): if date == None: saver.restore(self.session, "Trainings/" + env + "/" + time.strftime("%d%m%Y") + "/model.ckpt") with open("Trainings/" + env + "/" + time.strftime("%d%m%Y") + "/memory.txt", "rb") as fp: self.memory = pickle.load(fp) # Unpickling else: saver.restore(self.session, "Trainings/" + env + "/" + date + "/model.ckpt") with open("Trainings/" + env + "/" + date + "/memory.txt", "rb") as fp: self.memory = pickle.load(fp) # Unpickling print ("Networks loaded") <file_sep>/Asgeir_DDPG/ddpg_agent.py import gym from parameters import parse_args from ddpg import DDPG import numpy as np from collections import deque import matplotlib.pyplot as plt import tensorflow as tf import pickle import time import os def run_ddpg(): agent_params, ddpg_params, cnn_params, a_params, c_params = parse_args() env = gym.make(agent_params['environment']) episodes = agent_params['episodes'] action_frames = agent_params['action_frames'] steps = env.spec.timestep_limit if agent_params['steps'] > env.spec.timestep_limit else agent_params['steps'] action_shape = env.action_space.shape action_bound = env.action_space.high observation_shape = env.observation_space.shape tf.reset_default_graph() # Initialize buffer that stores Critic network losses, training and validation rewards statistics = [] if not os.path.exists("Trainings/" + agent_params['environment'] + "/" + time.strftime("%d%m%Y")): os.makedirs("Trainings/" + agent_params['environment'] + "/" + time.strftime("%d%m%Y")) with tf.Session() as session: ddpg = DDPG(action_shape, action_bound, observation_shape, ddpg_params, cnn_params, a_params, c_params, session) saver = tf.train.Saver() # Load the network and previously recorded statistics if agent_params['load'] == True: ddpg.load(saver, agent_params['environment']) with open("Trainings/" + agent_params['environment'] + "/" + time.strftime("%d%m%Y") + "/statistics.txt", "rb") as fp: # Unpickling statistics = pickle.load(fp) # Initialize ddpg learning else: ddpg.session.run(tf.global_variables_initializer()) ddpg.session.run(ddpg.C_copy_target) ddpg.session.run(ddpg.A_copy_target) print ("Prefilling memory") observation = env.reset() while len(ddpg.memory) < ddpg.memory.maxlen: action = env.action_space.sample() new_observation, reward, done, _ = env.step(action) ddpg.update_state(observation, action, new_observation, reward, done) observation = new_observation if not done else env.reset() for i_episode in range(len(statistics), episodes): # Select an initial observation from distribution of initial state env.seed(i_episode) observation = env.reset() frames = action_frames # Initialize buffers that stores the reward of a latest episode and the average loss of an episode r_training, C_loss_array, C_diff_array, A_diff_array = 0, [], [], [] for i in range(steps): # if i_episode % 10 == 0: env.render() if i_episode % 10 == 0 and i == 0 and i_episode != 0: ddpg.save(saver, agent_params['environment']) try: with open("Trainings/" + agent_params['environment'] + "/" + time.strftime("%d%m%Y") + "/statistics.txt", "wb") as fp: #Pickling pickle.dump(statistics, fp) except Exception: print ("Could not save!") # Select action based on the model if frames == action_frames: action = ddpg.select_action([observation], stochastic = True, target = False, step = i)[0] frames = 0 new_observation, reward, done, _ = env.step(action) # # Reward shaping # if agent_params['environment'] == 'CartPole-v0': # reward = reward - np.absolute(new_observation[0])/2.4 # if agent_params['environment'] == 'MountainCar-v0': # if i == 0: max_distance = 1 # max_distance = max(0, min(max_distance, np.absolute(new_observation[0] - 0.5)/1.7)) # if done: reward = -max_distance # Update the state frames += 1 if frames == action_frames: ddpg.update_state(observation, action, new_observation, reward, done) _C_loss, _C_diff, _A_diff = ddpg.train_step() C_loss_array.append(_C_loss) C_diff_array.append(_C_diff) A_diff_array.append(_A_diff) r_training += reward if done: if frames != action_frames: ddpg.update_state(observation, action, new_observation, reward, done) _C_loss, _C_diff, _A_diff = ddpg.train_step() C_loss_array.append(_C_loss) C_diff_array.append(_C_diff) A_diff_array.append(_A_diff) r_training += reward frames = action_frames break # Observation becomes new observation observation = new_observation # Calculate the average loss of previous training episode C_loss = np.mean(C_loss_array) C_diff = np.mean(C_diff_array) A_diff = np.mean(A_diff_array ) # Validation r_validation = 0 observation = env.reset() frames = action_frames for t in range(steps): # if i_episode % 10 == 0: env.render() if frames == action_frames: action = ddpg.select_action([observation], False, False)[0] frames = 0 new_observation, reward, done, _ = env.step(action) # Reward shaping # if agent_params['environment'] == 'CartPole-v0': # reward = reward - np.absolute(new_observation[0])/2.4 # if agent_params['environment'] == 'MountainCar-v0': # if i == 0: max_distance = 1 # max_distance = max(0, min(max_distance, np.absolute(new_observation[0] - 0.5)/1.7)) # if done: reward = -max_distance frames += 1 if frames == action_frames: r_validation += reward observation = new_observation if done: if frames != action_frames: r_validation += reward break statistics.append((r_training, r_validation, C_loss, C_diff, A_diff)) print('%4d. training reward: %6.2f, validation reward: %6.2f, C loss: %7.4f, C diff: %7.4f, A diff: %7.4f' % (i_episode+1, r_training, r_validation, C_loss, C_diff, A_diff)) # env.monitor.close() ddpg.save(saver, agent_params['environment']) try: with open("Trainings/" + agent_params['environment'] + "/" + time.strftime("%d%m%Y") + "/statistics.txt", "wb") as fp: #Pickling pickle.dump(statistics, fp) except Exception: print ("Could not save!") # Plot training statistics statistics = np.array(statistics).T mean_training_rewards = statistics[0] mean_validation_rewards = statistics[1] C_losses = statistics[2] C_diffs = statistics[3] A_diffs = statistics[4] plt.subplot(221) plt.plot(C_losses, label='C loss') plt.xlabel('epoch'); plt.ylabel('loss') plt.xlim((0, len(C_losses))) plt.legend(loc=1); plt.grid() plt.subplot(222) plt.plot(C_diffs, label='C diff') plt.xlabel('epoch'); plt.ylabel('difference') plt.xlim((0, len(C_diffs))) plt.legend(loc=1); plt.grid() plt.subplot(223) plt.plot(A_diffs, label='A diff') plt.xlabel('epoch'); plt.ylabel('difference') plt.xlim((0, len(A_diffs))) plt.legend(loc=1); plt.grid() plt.subplot(224) plt.plot(mean_training_rewards, label='mean training reward') plt.plot(mean_validation_rewards, label='mean validation reward') plt.xlabel('epoch'); plt.ylabel('mean reward') plt.xlim((0, len(mean_validation_rewards))) plt.legend(loc=4); plt.grid() plt.tight_layout(); plt.show() if __name__ == '__main__': run_ddpg() <file_sep>/README.md # RL Workspace for 02456 Deep Learning Repository appendix component of Project 23 Reinforcement Learning for the DTU Deep Learning course (2017). Contributors: <NAME>, <NAME>, <NAME> ## Information Repo contains coding implementation and results for Deep Determinisitic Policy Gradient (DDPG) and Proximal Policy Gradient (PPO) deep learning algorithms. <file_sep>/Fletcher_PPO/README.md # <NAME> Submission ## Instructions 1. Results and code can be viewed using this repo, however the ROS integration of Gazebo and some special plugins are required to perform training and validation of the policy and value function networks. 2. Run resultsplotter.m in MATLAB to view the training curves of all attempts at the AUV, Pendulum, and Mountain Car Continuous environments. 3. fakegym.py is the interface between the simulator and the network, ROS requires python 2.7 to work properly, so please run any .py files using python2. Browse through the different timestamped folders in AUVSim-v0 to see the different reward functions and stopping conditions trialed. 4. You can modify resultsplotter.m to view different logged variables (you can see all logged options from the 'headers' cell array in MATLAB). ## Further Information + The code used in this repo is adapted from [<NAME>'s Github](https://github.com/pat-coady/trpo). + Email <EMAIL> for further information about the simulator integration. + See AUVSim-v0/Dec-30_23-15-41 for a .ipynb implementation of the trainer. <file_sep>/Fletcher_PPO/AUVSim-v0/Dec-30_23-15-41/ppo.py """ Main Script for Running PPO Algorithm on AUVSim-v0 Adapted from work by <NAME> (pat-coady.github.io) Author: <NAME> """ import fakegym import numpy as np from policy import Policy from value_function import NNValueFunction import scipy.signal from utils import Logger, Scaler from datetime import datetime import os import argparse import signal import tensorflow as tf from IPython.lib import backgroundjobs as bg ## FUNCTION DECLARATIONS ## def discount(x, gamma): """ Calculate discounted forward sum of a sequence at each point """ return scipy.signal.lfilter([1.0], [1.0, -gamma], x[::-1])[::-1] def add_disc_sum_rew(trajectories, gamma): """ Adds discounted sum of rewards to all time steps of all trajectories Args: trajectories: as returned by run_policy() gamma: discount Returns: None (mutates trajectories dictionary to add 'disc_sum_rew') """ for trajectory in trajectories: if gamma < 0.999: # don't scale for gamma ~= 1 rewards = trajectory['rewards'] * (1 - gamma) else: rewards = trajectory['rewards'] disc_sum_rew = discount(rewards, gamma) trajectory['disc_sum_rew'] = disc_sum_rew def add_value(sess, trajectories, val_func): """ Adds estimated value to all time steps of all trajectories Args: trajectories: as returned by run_policy() val_func: object with predict() method, takes observations and returns predicted state value Returns: None (mutates trajectories dictionary to add 'values') """ for trajectory in trajectories: observes = trajectory['observes'] values = val_func.predict(sess,observes) trajectory['values'] = values def add_gae(trajectories, gamma, lam): """ Add generalized advantage estimator. https://arxiv.org/pdf/1506.02438.pdf Args: trajectories: as returned by run_policy(), must include 'values' key from add_value(). gamma: reward discount lam: lambda (see paper). lam=0 : use TD residuals lam=1 : A = Sum Discounted Rewards - V_hat(s) Returns: None (mutates trajectories dictionary to add 'advantages') """ for trajectory in trajectories: if gamma < 0.999: # don't scale for gamma ~= 1 rewards = trajectory['rewards'] * (1 - gamma) else: rewards = trajectory['rewards'] values = trajectory['values'] # temporal differences tds = rewards - values + np.append(values[1:] * gamma, 0) advantages = discount(tds, gamma * lam) trajectory['advantages'] = advantages def build_train_set(trajectories): """ Args: trajectories: trajectories after processing by add_disc_sum_rew(), add_value(), and add_gae() Returns: 4-tuple of NumPy arrays observes: shape = (N, obs_dim) actions: shape = (N, act_dim) advantages: shape = (N,) disc_sum_rew: shape = (N,) """ observes = np.concatenate([t['observes'] for t in trajectories]) actions = np.concatenate([t['actions'] for t in trajectories]) disc_sum_rew = np.concatenate([t['disc_sum_rew'] for t in trajectories]) advantages = np.concatenate([t['advantages'] for t in trajectories]) # normalize advantages advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-6) return observes, actions, advantages, disc_sum_rew def log_batch_stats(observes, actions, advantages, disc_sum_rew, logger, episode): """ Log various batch statistics """ logger.log({'_mean_obs': np.mean(observes), '_min_obs': np.min(observes), '_max_obs': np.max(observes), '_std_obs': np.mean(np.var(observes, axis=0)), '_mean_act': np.mean(actions), '_min_act': np.min(actions), '_max_act': np.max(actions), '_std_act': np.mean(np.var(actions, axis=0)), '_mean_adv': np.mean(advantages), '_min_adv': np.min(advantages), '_max_adv': np.max(advantages), '_std_adv': np.var(advantages), '_mean_discrew': np.mean(disc_sum_rew), '_min_discrew': np.min(disc_sum_rew), '_max_discrew': np.max(disc_sum_rew), '_std_discrew': np.var(disc_sum_rew), '_Episode': episode }) def run_episode(sess,env, policy, scaler): """ Run single episode Args: env: ai gym environment policy: policy object with sample() method scaler: scaler object, used to scale/offset each observation dimension to a similar range Returns: 4-tuple of NumPy arrays observes: shape = (episode len, obs_dim) actions: shape = (episode len, act_dim) rewards: shape = (episode len,) unscaled_obs: useful for training scaler, shape = (episode len, obs_dim) """ obs = env.reset() observes, actions, rewards, unscaled_obs = [], [], [], [] done = False step = 0.0 scale, offset = scaler.get() scale[-1] = 1.0 # don't scale time step feature offset[-1] = 0.0 # don't offset time step feature while not done: obs = obs.astype(np.float32).reshape((1, -1)) obs = np.append(obs, [[step]], axis=1) # add time step feature unscaled_obs.append(obs) obs = (obs - offset) * scale # center and scale observations observes.append(obs) action = policy.sample(sess, obs).reshape((1, -1)).astype(np.float32) actions.append(action) obs, reward, done, _ = env.step(np.squeeze(action, axis=0)) if not isinstance(reward, float): reward = np.asscalar(reward) rewards.append(reward) step += 5e-2 # increment time step feature return (np.concatenate(observes), np.concatenate(actions), np.array(rewards, dtype=np.float64), np.concatenate(unscaled_obs)) def run_policy(sess, env, policy, scaler, logger, episodes): """ Run policy and collect data for a minimum of min_steps and min_episodes Args: env: ai gym environment policy: policy object with sample() method scaler: scaler object, used to scale/offset each observation dimension to a similar range logger: logger object, used to save stats from episodes episodes: total episodes to run Returns: list of trajectory dictionaries, list length = number of episodes 'observes' : NumPy array of states from episode 'actions' : NumPy array of actions from episode 'rewards' : NumPy array of (un-discounted) rewards from episode 'unscaled_obs' : NumPy array of (un-discounted) rewards from episode """ print("Running Policy for {} Episodes".format(episodes)) total_steps = 0 trajectories = [] for e in range(episodes): observes, actions, rewards, unscaled_obs = run_episode(sess, env, policy, scaler) total_steps += observes.shape[0] trajectory = {'observes': observes, 'actions': actions, 'rewards': rewards, 'unscaled_obs': unscaled_obs} trajectories.append(trajectory) print("Episode: {}".format(e)) unscaled = np.concatenate([t['unscaled_obs'] for t in trajectories]) scaler.update(unscaled) # update running statistics for scaling observations logger.log({'_MeanReward': np.mean([t['rewards'].sum() for t in trajectories]), 'Steps': total_steps}) return trajectories ## RUN THE ENVIRONMENT ## env = fakegym.env() jobs = bg.BackgroundJobManager() # run the interface as a background process jobs.new('env.run()') ## SET HYPERPARAMETERS ## obs_dim = env.observation_space.shape[0] act_dim = env.action_space.shape[0] env_name="AUVSim-v0" model_dir = "tmp/model" hid1_mult=10 # sets size of first hidden layer as a multiple of observation dimension size kl_targ=0.006 # sets the maximum allowable KL divergence for the policy update policy_logvar=-1.0 # sets the initial log variance of the policy num_episodes = 50000 # stopping condition (total number of episodes) batch_size = 20 # number of trajectories to generate for each training session gamma = 0.995 # discount factor for future reward summation lam = 0.995 # general advantage estimation obs_dim += 1 # add 1 to the obs dimension for time now = datetime.utcnow().strftime("%b-%d_%H:%M:%S") # create unique directories logger = Logger(logname=env_name, now=now) scaler = Scaler(obs_dim) ## BUILD THE NETWORKS ## tf.reset_default_graph() G = tf.Graph() val_func = NNValueFunction(G,obs_dim, hid1_mult) policy = Policy(G, obs_dim, act_dim, kl_targ, hid1_mult, policy_logvar) ## INITIALIZE THE NETWORK VARIABLES ## config = tf.ConfigProto() config.gpu_options.per_process_gpu_memory_fraction = 0.5 with G.as_default(): sess = tf.Session(graph=G,config=config) sess.run(tf.global_variables_initializer()) saver = tf.train.Saver() writer = tf.summary.FileWriter("./tmp/log", G) # to visualise the graph through tensorboard print("***\nINFO: tensorboard visualisation\nrun 'tensorboard --logdir=tmp' in another terminal (from this directory) to visualise the networks\n***") # run a few episodes of random policy for observation normalisation: print("Generating random states to initialise the observation scaler") run_policy(sess,env, policy, scaler, logger, episodes=5) print("Beginning Training") episode = 0 while episode < num_episodes: print("Episode {} out of {}".format(episode,num_episodes)) trajectories = run_policy(sess,env, policy, scaler, logger, episodes=batch_size) episode += len(trajectories) add_value(sess, trajectories, val_func) # add estimated values to episodes add_disc_sum_rew(trajectories, gamma) # calculated discounted sum of rewards add_gae(trajectories, gamma, lam) # calculate advantage # concatenate all episodes into single NumPy arrays observes, actions, advantages, disc_sum_rew = build_train_set(trajectories) # add various stats to training log: log_batch_stats(observes, actions, advantages, disc_sum_rew, logger, episode) policy.update(sess,observes, actions, advantages, logger) # update policy val_func.fit(sess,observes, disc_sum_rew, logger) # update value function logger.write(display=True) # write logger results to file and stdout if episode % 1000 == 0: saver.save(sess, model_dir, global_step=i) #save the model every 1000 episodes logger.close() sess.close() env.close()<file_sep>/Fletcher_PPO/AUVSim-v0/Dec-24_11-20-31/fakegym.py import rospy import dynamic_reconfigure.client from sensor_msgs.msg import JointState from nav_msgs.msg import Odometry from gazebo_msgs.msg import ModelState from geometry_msgs.msg import PoseStamped from std_srvs.srv import Empty import tf.transformations as transform import random from math import pi, sqrt from gym import spaces from gym.envs.registration import EnvSpec import numpy as np class env(): def __init__(self,discrete=False,steplimit=1000): self.state = np.zeros(12) self.scale = 30.0 self.nh = rospy.init_node('fakegyminterface') self.steps = 0 self.steplimit = steplimit if discrete: self.action_space = spaces.Discrete(6) else: self.action_space = spaces.Box(low=-1, high=1, shape=(6,)) self.observation_space = spaces.Box(low=-200, high=200, shape=(12,)) self.spec = EnvSpec('AUVSim-v0',timestep_limit=self.steplimit) self.rng = random self.lastaction = [0.0,0.0,0.0,0.0,0.0,0.0] try: #Subscriber to get the model's pose & twist rospy.Subscriber('/brov/state', Odometry, self.updateState) #Publisher to set randomize the model pose & twist on each restart self.reset_pub = rospy.Publisher('/gazebo/set_model_state', ModelState, queue_size=1) self.target_pub = rospy.Publisher('/target', PoseStamped, queue_size=1) self.thrust_pub = rospy.Publisher('/brov/thruster_command', JointState, queue_size=1) self.step_srv = rospy.ServiceProxy('/gazebo/step', Empty) rospy.wait_for_service('/gazebo/step') self.step_srv() except rospy.ROSInterruptException: pass def updateState(self,newState): x = newState.pose.pose.position.x y = newState.pose.pose.position.y z = newState.pose.pose.position.z quat = ( newState.pose.pose.orientation.x, newState.pose.pose.orientation.y, newState.pose.pose.orientation.z, newState.pose.pose.orientation.w,) euler = transform.euler_from_quaternion(quat) #u = newState.twist.twist.linear.x #v = newState.twist.twist.linear.y #w = newState.twist.twist.linear.z #p = newState.twist.twist.angular.x #q = newState.twist.twist.angular.y #r = newState.twist.twist.angular.z self.state = np.array([x,y,z,euler[0],euler[1],euler[2]]+self.state[6:].tolist()) #self.state = np.array([x,y,z,euler[0],euler[1],euler[2],u,v,w,p,q,r]+self.state[6:].tolist()) def reset(self): #AUV State Message to send to the simulator zeroState = ModelState() zeroState.model_name = 'brov' zeroState.pose.position.x = self.rng.uniform(-100.0,100.0) zeroState.pose.position.y = self.rng.uniform(-100.0,100) zeroState.pose.position.z = self.rng.uniform(-200.0,0.0) r = self.rng.uniform(-pi,pi) p = self.rng.uniform(-pi,pi) y = self.rng.uniform(-pi,pi) quat = transform.quaternion_from_euler(r,p,y) zeroState.pose.orientation.x = quat[0] zeroState.pose.orientation.y = quat[1] zeroState.pose.orientation.z = quat[2] zeroState.pose.orientation.w = quat[3] zeroState.twist.linear.x = self.rng.uniform(-0.5,0.5) zeroState.twist.linear.y = self.rng.uniform(-0.5,0.5) zeroState.twist.linear.z = self.rng.uniform(-0.5,0.5) zeroState.twist.angular.x = self.rng.uniform(-0.1,0.1) zeroState.twist.angular.y = self.rng.uniform(-0.1,0.1) zeroState.twist.angular.z = self.rng.uniform(-0.1,0.1) #Send to the simulator self.reset_pub.publish(zeroState) #AUV Target Message to send to the simulator target = PoseStamped() target.pose.position.x = self.rng.uniform(-5,5)+zeroState.pose.position.x target.pose.position.y = self.rng.uniform(-5,5)+zeroState.pose.position.y target.pose.position.z = self.rng.uniform(-5,5)+zeroState.pose.position.z rd = self.rng.uniform(0,0) pd = self.rng.uniform(0,0) yd = self.rng.uniform(-pi,pi) quat = transform.quaternion_from_euler(rd,pd,yd) target.pose.orientation.x = quat[0] target.pose.orientation.y = quat[1] target.pose.orientation.z = quat[2] target.pose.orientation.w = quat[3] target.header.stamp = rospy.Time.now() target.header.frame_id = 'world' self.target_pub.publish(target) #Return the reset state state = [] state.append(zeroState.pose.position.x) state.append(zeroState.pose.position.y) state.append(zeroState.pose.position.z) state.append(r) state.append(p) state.append(y) #state.append(zeroState.twist.linear.x ) #state.append(zeroState.twist.linear.y ) #state.append(zeroState.twist.linear.z ) #state.append(zeroState.twist.angular.x) #state.append(zeroState.twist.angular.y) #state.append(zeroState.twist.angular.z) state.append(target.pose.position.x) state.append(target.pose.position.y) state.append(target.pose.position.z) state.append(rd) state.append(pd) state.append(yd) self.state = np.array(state) #restart the step counter self.steps=0 return self.state def step(self,action): #update the thrusts of the AUV thruster_msg = JointState() thruster_msg.name = ['thr1','thr2','thr3','thr4','thr5','thr6'] scaledaction = [self.scale*i for i in action] thruster_msg.position = [scaledaction[0],scaledaction[1],scaledaction[2],scaledaction[3], scaledaction[4],scaledaction[5]] self.lastaction = [scaledaction[0],scaledaction[1],scaledaction[2],scaledaction[3], scaledaction[4],scaledaction[5]] thruster_msg.header.stamp = rospy.Time.now() thruster_msg.header.frame_id = 'base_link' self.thrust_pub.publish(thruster_msg) #perform the stepping operation rospy.wait_for_service('/gazebo/step') self.step_srv() #increment the step by 1 self.steps+=1 #calculate the stopping criteria #distance2target = sqrt((self.state[0]-self.state[12])**2 # +(self.state[1]-self.state[13])**2+(self.state[2]-self.state[14])**2) #angle2target = sqrt((self.state[3]-self.state[15])**2+(self.state[4]-self.state[16])**2 # +(self.state[5]-self.state[17])**2) #speed2target = sqrt((self.state[6])**2+(self.state[7])**2+(self.state[8])**2) #angspeed2target =sqrt((self.state[9])**2+(self.state[10])**2+(self.state[11])**2) distance2target = sqrt((self.state[0]-self.state[6])**2 +(self.state[1]-self.state[7])**2+(self.state[2]-self.state[8])**2) angle2target = sqrt((self.state[3]-self.state[9])**2+(self.state[4]-self.state[10])**2 +(self.state[5]-self.state[11])**2) #done is true if the steps are greater than the limit, or if the distance, angles and speeds are within acceptable limits done = self.steps>self.steplimit or (distance2target<0.1 and angle2target<0.01) #done = self.steps>self.steplimit or (distance2target<0.1 and angle2target<0.05 and speed2target<0.1 and angspeed2target<0.05) return np.array(self.state), self.reward(), done, "don't look here" def reward(self): #rollerr = abs(self.state[3]-self.state[15]) #pitcherr = abs(self.state[4]-self.state[16]) #yawerr = abs(self.state[5]-self.state[17]) #xerr = abs(self.state[0]-self.state[12]) #yerr = abs(self.state[1]-self.state[13]) #zerr = abs(self.state[2]-self.state[14]) rollerr = abs(self.state[3]-self.state[9]) pitcherr = abs(self.state[4]-self.state[10]) yawerr = abs(self.state[5]-self.state[11]) xerr = abs(self.state[0]-self.state[6]) yerr = abs(self.state[1]-self.state[7]) zerr = abs(self.state[2]-self.state[8]) # MAXIMUM REWARD PER STEP = 1 (eroll epitch eyaw ex ey ez = 0) PoseObj = 1.0/(rollerr+pitcherr+yawerr+xerr+yerr+zerr+1) TimeObj = -1.0 #RotationObj = 1.0/(rollerr+pitcherr+yawerr+1e-2) #EnergyObj = 1.0/(np.array(self.lastaction).sum()+1e-2) # MAXIMUM REWARD PER STEP = 1 + -1 = 0 -> TOTAL REWARD FOR 1 EPISODE RANGES FROM -960 to 0 return PoseObj+TimeObj#+RotationObj+EnergyObj def seed(self,i): self.rng.seed(i) def close(self): rospy.signal_shutdown("close method called, stopping node")
1a6ce2bbd750db01e6a02c89e4a300cafee5ec35
[ "Markdown", "Python", "Text" ]
12
Python
FletcherFT/RL
cd646a3d1a78d93d639c0c1acfedff167f508f98
bf7f25fc98aa40d1b3b9345439be2d272443e411
refs/heads/master
<file_sep>/* 我们正在玩一个猜数字游戏。 游戏规则如下: 我从 1 到 n 选择一个数字。 你需要猜我选择了哪个数字。 每次你猜错了,我会告诉你这个数字是大了还是小了。 你调用一个预先定义好的接口 guess(int num),它会返回 3 个可能的结果(-1,1 或 0): -1 : 我的数字比较小 1 : 我的数字比较大 0 : 恭喜!你猜对了! 示例 : 输入: n = 10, pick = 6 输出: 6 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/guess-number-higher-or-lower 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ /** * Forward declaration of guess API. * @param {number} num your guess * @return -1 if num is lower than the guess number * 1 if num is higher than the guess number * otherwise return 0 * var guess = function(num) {} */ /** * @param {number} n * @return {number} */ var guessNumber = function (n) { let min = 1, max = n; n = Math.floor((min + max) / 2); let result = guess(n); while (result !== 0) { if (result === -1) { max = Math.min(n - 1, max) } else { min = Math.max(n + 1, min) } n = Math.floor((min + max) / 2); result = guess(n); } return n; }; <file_sep>/* 编写一个算法来判断一个数 n 是不是快乐数。 「快乐数」定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。如果 可以变为 1,那么这个数就是快乐数。 如果 n 是快乐数就返回 True ;不是,则返回 False 。 示例: 输入:19 输出:true 解释: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1 */ /** * @param {number} n * @return {boolean} */ var isHappy = function (num) { const resultTable = new Set(); while (num !== 1 && !resultTable.has(num)) { resultTable.add(num) num = String(num).split('').map(n => Math.pow(Number(n), 2)).reduce((a, b) => a + b, 0); } return num === 1; }; console.log(isHappy(19))<file_sep>/* 我们定义了一个函数 countUniqueChars(s) 来统计字符串 s 中的唯一字符,并返回唯一字符的个数。 例如:s = "LEETCODE" ,则其中 "L", "T","C","O","D" 都是唯一字符,因为它们只出现一次,所以 countUniqueChars(s) = 5 。 本题将会给你一个字符串 s ,我们需要返回 countUniqueChars(t) 的总和,其中 t 是 s 的子字符串。注意,某些子字符串可能是重复的,但你统计时也必须算上这些重复的子字符串(也就是说,你必须统计 s 的所有子字符串中的唯一字符)。 由于答案可能非常大,请将结果 mod 10 ^ 9 + 7 后再返回。   示例 1: 输入: "ABC" 输出: 10 解释: 所有可能的子串为:"A","B","C","AB","BC" 和 "ABC"。 其中,每一个子串都由独特字符构成。 所以其长度总和为:1 + 1 + 1 + 2 + 2 + 3 = 10 示例 2: 输入: "ABA" 输出: 8 解释: 除了 countUniqueChars("ABA") = 1 之外,其余与示例 1 相同。 示例 3: 输入:s = "LEETCODE" 输出:92   提示: 0 <= s.length <= 10^4 s 只包含大写英文字符 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/count-unique-characters-of-all-substrings-of-a-given-string 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ /** * @param {string} s * @return {number} */ var uniqueLetterString = function (s = '') { const maxCount = new Set(s.split('')).size; let num = 0; for (let i = 0; i < s.length; i++) { const black = {}; const white = { [s[i]]: 1 }; let whiteNum = 1, blackNum = 0; num += whiteNum; for (let j = i + 1; j < s.length; j++) { let c = s[j]; if (blackNum === maxCount) break; if (black[c]) { //nothing } else if (white[c]) { whiteNum--; black[c] = 1; blackNum++; } else { whiteNum++; white[c] = 1; } num += whiteNum; } } return num; } console.log(uniqueLetterString('ABC'), 10) console.log(uniqueLetterString('ABA'), 8) console.log(uniqueLetterString('LEETCODE'), 92) <file_sep>/* 给定一个编码字符串 S。为了找出解码字符串并将其写入磁带,从编码字符串中每次读取一个字符,并采取以下步骤: 如果所读的字符是字母,则将该字母写在磁带上。 如果所读的字符是数字(例如 d),则整个当前磁带总共会被重复写 d-1 次。 现在,对于给定的编码字符串 S 和索引 K,查找并返回解码字符串中的第 K 个字母。   示例 1: 输入:S = "leet2code3", K = 10 输出:"o" 解释: 解码后的字符串为 "leetleetcodeleetleetcodeleetleetcode"。 字符串中的第 10 个字母是 "o"。 示例 2: 输入:S = "ha22", K = 5 输出:"h" 解释: 解码后的字符串为 "hahahaha"。第 5 个字母是 "h"。 示例 3: 输入:S = "a2345678999999999999999", K = 1 输出:"a" 解释: 解码后的字符串为 "a" 重复 8301530446056247680 次。第 1 个字母是 "a"。   提示: 2 <= S.length <= 100 S 只包含小写字母与数字 2 到 9 。 S 以字母开头。 1 <= K <= 10^9 解码后的字符串保证少于 2^63 个字母。 通过次数2,696提交次数11,672 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/decoded-string-at-index 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ /** * @param {string} S * @param {number} K * @return {string} */ var decodeAtIndex = function (S, K) { let cal = [], nowLength = 0; let nowNode = null; for (let c of S) { if (c >= '2' && c <= '9') { nowNode.times = nowNode.times * Number(c); } else { if (!nowNode) { nowNode = { head: null, str: c, times: 1, length: 1 }; } else { if (nowNode.times !== 1) { nowNode = { head: nowNode, str: c, times: 1, length: nowNode.length * nowNode.times + 1 }; } else { nowNode.str += c; nowNode.length++; } } } if (nowNode.length * nowNode.times >= K) { let d = K -1; while (nowNode) { d = d % nowNode.length; if (d >= nowNode.length - nowNode.str.length) { return nowNode.str[d - (nowNode.length - nowNode.str.length) ]; } else { nowNode = nowNode.head; } } } } }; <file_sep># solvingcode 对`leetcode`解题的一些记录,基本不会留注释,有空就做一些题免得脑子生锈 个人页面 [https://leetcode-cn.com/u/ngtmuzi/](https://leetcode-cn.com/u/ngtmuzi/)
18e28e5b805446aa90f752372b6cf10b648a2e0b
[ "JavaScript", "Markdown" ]
5
JavaScript
ngtmuzi/solvingcode
9c07cf200943d0d2e200331e66e3e8d3f3d178fd
89ef52f5c2615906180f7409120fbc505738bfdd