branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/main
<repo_name>Atharva-Phatak/A2OJ<file_sep>/README.md # A2OJ Solutions to A2OJ Ladders <file_sep>/codeforces-1300/young-physicst.py n = int(input()) l = [] for _ in range(n): l.append(list(map(int , input().split()))) ans = [sum(col) for col in zip(*l)] if any(ans): print("NO") else: print("YES")
3afef998cdd0923d89983506b286b6ed11b14178
[ "Markdown", "Python" ]
2
Markdown
Atharva-Phatak/A2OJ
d2d20c53236fba1e4b4a7cc8465b4fe03bedd7e2
26f3302e2c3d7721914f460950f0bab816597233
refs/heads/main
<repo_name>michaelvangelovski/wp-tus<file_sep>/wp-tus.php <?php /** * Plugin Name: WP Tus * Plugin URI: <plugin URI> * Description: Tus Server in WordPress. * Version: 0.0.0 * Author: <author name> * Author URI: <author URI> * License: GPL2 or later * License URI: http://www.gnu.org/licenses/gpl-2.0.html */ // Avoid direct calls to this file. if ( ! defined( 'ABSPATH' )) { header( 'Status: 403 Forbidden' ); header( 'HTTP/1.1 403 Forbidden' ); die( 'Access Forbidden' ); } require __DIR__ . '/vendor/autoload.php'; add_action( 'init', function () { add_rewrite_tag( '%tus%', '([^&]+)' ); add_rewrite_rule( '^wp-tus/([^/]*)/?', 'index.php?tus=$matches[1]', 'top' ); add_rewrite_rule( '^wp-tus/?', 'index.php?tus', 'top' ); } ); add_action('parse_request', function ( $wp ) { // Return if it is a normal request. if ( ! isset($wp->query_vars['tus'])) { return; } \TusPhp\Config::set([ 'file' => [ 'dir' => '/tmp/', 'name' => 'tus_php.cache', ], ]); $server = new \TusPhp\Tus\Server(); $server ->setApiPath( '/wp-tus' ) // tus server endpoint. ->setUploadDir( __DIR__ . '/../../../../wp-tus-uploads' ); $response = $server->serve(); $response->send(); } );
ac6249424c390dfae6ec30bfc4894d3da6156faa
[ "PHP" ]
1
PHP
michaelvangelovski/wp-tus
1979dde42b5a2c2cbcc42755f30962975a549103
2ffaaaa5c2c7b481d7aa215f033ab7d0e4487cd3
refs/heads/master
<repo_name>itshosted/smtpw<file_sep>/smtpw.sh #!/bin/bash # /etc/rc.d/init.d/smtpw # # Init.d (CentOS) script for spawning smtpw. # . /etc/init.d/functions SERVICE="smtpw" DIR="/storage/smtpw" USER="$SERVICE" LOG="/var/log/$SERVICE" PSNAME="smtpw -c=./config.json" status() { ps aux | grep -v grep | grep "$PSNAME" > /dev/null # Invert OK="$?" return $OK } start() { if status then echo "$SERVICE already running." exit 1 fi mkdir -p "$LOG" echo -n "Starting $SERVICE: " daemon --user="$USER" "$DIR/smtpw -c=\"./config.json\" &" 1>$LOG/stdout.log 2>$LOG/stderr.log RETVAL=$? echo "" return $RETVAL } stop() { if status then echo -n "Shutting down $SERVICE: " ps -ef | grep "$PSNAME" | grep -v grep | awk '{print $2}' | xargs kill -s SIGINT exit $? fi echo "$SERVICE is not running" exit 1 } case "$1" in start) start ;; stop) stop ;; status) if status then echo "$SERVICE is running." else echo "$SERVICE is not running." fi ;; restart) stop start ;; *) echo "Usage: $0 {start|stop|restart}" exit 1 ;; esac <file_sep>/test/test.php <?php function msg($msg) { echo $msg . "\n"; } $json = file_get_contents(__DIR__ ."/test.json"); $len = strlen($json); $fd = fsockopen("127.0.0.1", "11300", $errno, $errstr, 10); if (! $fd) { die(sprintf("%d - %s", $errno, $errstr)); } fwrite($fd, "use email\r\n"); msg(stream_get_line($fd, 999999999999, "\r\n")); fwrite($fd, "put 100 0 1 $len\r\n"); fwrite($fd, "$json\r\n"); msg(stream_get_line($fd, 999999999999, "\r\n")); fwrite($fd, "quit\r\n"); fclose($fd); <file_sep>/config/config.go package config // Read config.json import ( "fmt" "github.com/jinzhu/configor" ) // From struct type From struct { User string Pass string Host string Port int From string Display string Bcc []string Bounce *string Hostname string Insecure bool } // Config struct type Config struct { Beanstalk string `default:"127.0.0.1:11300"` From map[string]From } // Email struct type Email struct { From string To []string Subject string Html string Text string HtmlEmbed map[string]string // file.png => base64(bytes) Attachments map[string]string // file.png => base64(bytes) } var ( // C contains Config struct C Config ) // Init will read and parse config func Init(f string) error { e := configor.New(&configor.Config{ENVPrefix: "SMTPW"}).Load(&C, f) if e != nil { return fmt.Errorf("Config error: %s", e) } return nil } <file_sep>/go.mod module smtpw go 1.15 require ( github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf github.com/jinzhu/configor v1.2.1 github.com/mpdroog/beanstalkd v0.0.0-20150714195341-dcc9264e58e3 gopkg.in/alexcesaro/quotedprintable.v2 v2.0.0-20150314193201-9b4a113f96b3 // indirect gopkg.in/gomail.v1 v1.0.0-20150320132819-11b919ab4933 ) <file_sep>/Dockerfile FROM golang:1.16 AS builder WORKDIR /go/src/smtpw/ COPY . . RUN go get RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -installsuffix cgo -ldflags="-extldflags '-static' -X main.version=$(git describe --always --long --dirty --all)-$(date +%Y-%m-%d-%H:%M)" -o smtpw FROM scratch LABEL MAINTAINER <NAME> <<EMAIL>> WORKDIR /app COPY --from=builder /go/src/smtpw/smtpw /app/ CMD ["./smtpw"]
6d128ea14b49ba663e108cce4d431cb7d66bf3d0
[ "PHP", "Go", "Go Module", "Dockerfile", "Shell" ]
5
Shell
itshosted/smtpw
18bba7533e7e788d3a7fe0b0be8790a437c67a8b
701518f8cedbf40672855eba182f7ddb3bf8a3c7
refs/heads/master
<repo_name>rajvaya/letschat<file_sep>/src/config.js const Config = { apiKey: "<KEY>", authDomain: "letschat-1111.firebaseapp.com", databaseURL: "https://letschat-1111-default-rtdb.firebaseio.com", projectId: "letschat-1111", storageBucket: "letschat-1111.appspot.com", messagingSenderId: "5275177404", appId: "1:5275177404:web:f81a162ec4c3b0647f1bb9", }; export default Config<file_sep>/src/Components/ChatInput.jsx import React, { useEffect } from 'react' import firebase from './../firebase' import "firebase/database" import { useLocation } from 'react-router-dom' const ChatInput = ({ currentUser, status, chatID }) => { const [Text, setText] = React.useState(""); const textHandler = (e) => { e.preventDefault(); console.log(e.target.value); setText(e.target.value); }; var time = Date.now || function () { return +new Date; }; function send() { var MessagesRef = firebase.database().ref(`chats/${chatID}`); var newMessageRef = MessagesRef.push(); newMessageRef.set({ sender: currentUser, message: Text, timestamp: time(), status: (status === "offline") ? "sent" : "delivered", }); setText(""); } return ( <div className="flex flex-row"> <input type="text" name="tweeturl/id" value={Text} onChange={textHandler} placeholder="Write your Message" autoCapitalize="none" className="border-2 border-blue-700 p-2 flex-1" /> <button className="border-2 border-blue-700 p-2" onClick={ send }>SEND</button> </div> ) } export default ChatInput <file_sep>/src/App.jsx import React, { useEffect, useState } from 'react' import './App.css' import Users from './Pages/Users'; import { BrowserRouter as Router, Switch, Route, Redirect, } from "react-router-dom" import Home from './Pages/home'; import ChatBox from './Pages/ChatBox'; function App() { useEffect(() => { }, []); return ( <Router> <Switch> <Route exact path="/"> <Home /> </Route> <Route exact path="/users/:id"> <Users /> </Route> <Route exact path="/users/:id/chat"> <ChatBox /> </Route> <Redirect path="*" to="/" /> </Switch> </Router> ) } export default App <file_sep>/src/Components/Message.jsx import React from "react"; import classNames from "classnames"; import { useLocation } from "react-router-dom"; const Message = ({ currentUser , msg }) => { const location = useLocation(); console.log(msg); function getColor() { return (currentUser === msg.sender) ? "border-green-500" : "border-pink-500"; } function timeStampToDate(timestamp) { var date = new Date(timestamp); return " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds(); } return ( <div className={classNames( "flex flex-col m-2 border-4 rounded-xl p-2 whitespace-pre-wrap wrap break-words", getColor() )} > <p> {msg.message} </p> <div className="flex flex-row justify-between"> <p> time : {timeStampToDate(msg.timestamp)} </p> {currentUser === msg.sender ? ( <p className="text-right"> {msg.status} </p> ) : ( <></> )} </div> </div> ); }; export default Message;
3c72d0403de391766126805b218800146cf2d1f0
[ "JavaScript" ]
4
JavaScript
rajvaya/letschat
442d166ac1387042ede11fb5c3a35a202df201a7
86e0c3f2f9a4622e137b0e2e8772790188c7c755
refs/heads/master
<file_sep><?php /** * Created by PhpStorm. * User: 启天 * Date: 2017/10/17 * Time: 17:49 */ namespace app\common\validate; use think\Validate; class AdminUser extends Validate{ protected $rule = [ 'username' => 'require|max:25', 'password' => '<PASSWORD>', 'phone' => 'number|max:11', 'email' => 'email', ]; }<file_sep><?php /** * Created by PhpStorm. * User: yoyo * Date: 2017/10/12 * Time: 15:03 */ namespace app\admin\controller; use think\Controller; use think\Request; class Admin extends Controller { /** * 后台添加用户 */ public function add(){ // halt($data);//相当于dump($data);die();//dump(input('post.'));相当于dump() if (request()->isPost()){ $data = input('post.'); // 获取表单上传文件 例如上传了001.jpg $img = collection(request()->file('avator'))->toArray(); //获取图像信息将原图保持页面剪裁前的尺寸 //用页面传的尺寸剪裁图片 //调用剪裁方法处理图片并返回 $image = \think\Image::open('./image.png'); //将图片裁剪为150x150,从w,h处开始剪裁并保存为crop.png $crop = $image->crop(150, 150, $data['w'], $data['h']); $pub = new Pub(); $data['avator'] = $pub->cropAvator($crop.'png'); //上传剪裁好的图片并返回存储路径,保存至数据库 $uploads = new Pub(); $data['avator'] = $uploads->upload($img); // $data['avator'] = request()->file('avator'); $validate = validate('AdminUser');//加载验证类 //检测参数 if(!$validate->check($data)){ $this->error($validate->getError()); } $salt = $this->getRandomString('4');//获取随机盐值 $data['password'] = password_hash($data['password'].$salt, PASSWORD_BCRYPT);//加密处理 $data['status'] = '0';//状态:0正常;1删除 try { $id = model('AdminUser')->add($data); }catch (\Exception $e){ return $e->getMessage(); } if(!isset($id)){ } }else{ return $this->fetch(); } } }<file_sep><?php /** * Created by PhpStorm. * User: 启天 * Date: 2017/10/18 * Time: 13:55 */ namespace app\common\model; use think\Model; class AdminUser extends Model { protected $autoWriteTimestamp = true;//开启器时间自动写入 /** * 新增用户 */ public function add($data){ //判断当前参数是否是数组 if (!is_array($data)){ exception('传递数据不合法'); } //保存数据并返回该条记录id $this->allowField(true)->save($data); $result = $this->getLastSql(); dump($result);exit(); // return $this->id; } }<file_sep><?php /** * Created by PhpStorm. * User: 启天 * Date: 2017/10/23 * Time: 14:05 */ namespace app\admin\controller; use think\Controller; class Pub extends Controller{ /** * 剪裁头像 */ /* public function cutAvator(){ if ($_SERVER['REQUEST_METHOD'] == 'POST') { $targ_w = $targ_h = 150; $jpeg_quality = 90; $src = 'uploads/pool.jpg'; $img_r = imagecreatefromjpeg($src); $dst_r = ImageCreateTrueColor( $targ_w, $targ_h ); imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'], $targ_w,$targ_h,$_POST['w'],$_POST['h']); header('Content-type: image/jpeg'); $avator = imagejpeg($dst_r,null,$jpeg_quality); return $avator; } }*/ public function cropAvator(){ } /** * 上传 */ public function upload($file){ // 获取表单上传文件 例如上传了001.jpg // $file = request()->file('image'); // 验证图片格式大小,移动到框架应用根目录/uploads/avator 目录下 if($file){ $info = $file->validate(['size'=>3145728,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'uploads' . DS . 'avator'); if($info){ // 成功上传后 获取上传信息 // 输出 jpg return $info->getExtension(); // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg return $info->getSaveName(); // 输出 42a79759f284b767dfcb2a0197904287.jpg return $info->getFilename(); }else{ // 上传失败获取错误信息 return $file->getError(); } } } }
9ca6c9ae412122ca8ff438aa9bbeee6e4682d4a4
[ "PHP" ]
4
PHP
suqinglin113x/WhyMews
be67134da9d8b8da45d8db050f83b2e92a8ff51c
5558766094d7593b4f68e0764ab1d20720063c47
refs/heads/master
<repo_name>essjay05/WDI-SM-62_w09-d04_rails-blog-LAB<file_sep>/db/seeds.rb # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) posts = Post.create([ {title: "First post", content:"Today we learned rails association between models."}, {title: "Second post", content:"I'm so far liking ruby and rails thus far..."}, {title: "Third post", content:"We will next be learning about React."} ])
c9e9f6bfbc73bd324c1504f63fe83cae9e5cbd57
[ "Ruby" ]
1
Ruby
essjay05/WDI-SM-62_w09-d04_rails-blog-LAB
5e5255911f9866675111ce6c6120999e9f78a667
ba671f890b9c6dc3b1694fc6bc0249c8c2bcc5f8
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import { FAKER_TYPES } from './faker-type'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'] }) export class HomeComponent implements OnInit { typeList = [ { name: 'number', displayName: 'Number' } ]; JSONSchema: any; fields = []; fakerTypes = FAKER_TYPES; fakerTypeList = []; sampleJSONSchema = `{ "$id": "https://example.com/person.schema.json", "$schema": "http://json-schema.org/draft-07/schema#", "title": "Person", "type": "object", "properties": { "firstName": { "type": "string", "description": "The person's first name." }, "lastName": { "type": "string", "description": "The person's last name." }, "age": { "description": "Age in years which must be equal to or greater than zero.", "type": "integer", "minimum": 0 } } }`; constructor() { this.JSONSchema = JSON.parse(this.sampleJSONSchema); this.fields = Object.keys(this.JSONSchema.properties); this.fakerTypeList = Object.keys(this.fakerTypes); } ngOnInit() { } }
3de525666e25b66201a22f5392977af81102ee6f
[ "TypeScript" ]
1
TypeScript
thai2902/faker-ui
8a87c6b048b7c806defe8cb5171661a026ad9e63
14c6a02268b147b869081f355b304b30872bfbc4
refs/heads/master
<repo_name>NorbertCseh/mevn-chat<file_sep>/api/room/RoomApi.js const express = require('express') const passport = require('passport') const router = express.Router() const Room = require('../../models/Room') const User = require('../../models/User') const validator = require('validator') router.post( '/create-room', passport.authenticate('jwt', { session: false }), (req, res) => { if (validator.isEmpty(req.body.name)) { res.status(400).json({ Error: 'Name cannot be empty' }) } else if (validator.isEmpty(req.user.id)) { res.status(400).json({ Error: 'You are not logged in' }) } else { Room.findOne({ name: req.body.name }).then(room => { if (room) { res.status(400).json({ Error: 'Name already exists' }) } else { newRoom = new Room({ name: req.body.name, avatar: validator.isURL(req.body.avatar) ? req.body.avatar : 'https://www.hotukdeals.com/assets/img/profile-placeholder_f56af.png', createdBy: req.user.id, members: [req.user.id] }) newRoom .save() .then(newRoom => { res.status(201).json({ _id: newRoom._id, msg: `${newRoom.name} is created` }) }) .catch(err => { res.status(400).json({ Error: err }) }) } }) } } ) router.put( '/add-member/:room_id', passport.authenticate('jwt', { session: false }), (req, res) => { if (validator.isEmpty(req.body.displayName)) { res.status(400).json({ Error: 'Field cannot be empty' }) } else { Room.findOne({ _id: req.params.room_id }).then(room => { if (!room) { res.status(400).json({ Error: 'There is no room like this WTF' }) } else { User.findOne({ displayName: req.body.name }).then(user => { if (!user) { res.status(400).json({ Error: 'No user like this' }) } else { if (room.members.includes(user._id)) { res .status(400) .json({ Error: `She/He is already member of ${room.name}` }) } else { room.members.push(user._id) room .save() .then(room => { res .status(200) .json(`${req.user.displayName} added to ${room.name}`) }) .catch(err => res.status(400).json({ Error: err })) } } }) } }) } } ) //Should send back the data that the room already have and display it router.post( '/edit-room/:room_id', passport.authenticate('jwt', { session: false }), (req, res) => { Room.findOne({ name: req.body.name }) .then(room => room ? res.status(400).json({ Error: 'Room name already taken' }) : null ) .catch(err => console.log(err)) Room.findOne({ _id: req.param.room_id }).then(room => { if (!room.members.includes(req.user._id)) { res .status(400) .json({ Error: "You don't have the permission to edit this room" }) } else { room = { name: req.body.name, members: req.body.members, password: <PASSWORD>, avatar: req.body.avatar } room .save() .then(room => { res.status(200).json(`${room.name} was successfully edited`) }) .catch(err => { res.status(400).json({ Error: err }) }) } }) } ) router.delete( '/delete-room/:room_id', passport.authenticate('jwt', { session: false }), (req, res) => { Room.findOne({ _id: req.param.room_id }).then(room => { if (!room.createdBy === req.user._id) { res .status(400) .json( 'You do not have permission to delete this room. Only the creator can delete it.' ) } else { room .remove() .then(() => { res.status(200).json({ msg: 'Room successfully deleted' }) }) .catch(err => { res.status(400).json({ Error: err }) }) } }) } ) router.get( '/:room_id', passport.authenticate('jwt', { session: false }), (req, res) => { Room.findOne({ _id: req.params.room_id }).then(room => { if (!room) { res.status(400).json({ Error: 'Room does not exists' }) } else { if (!room.members.includes(req.user.id)) { res .status(400) .json({ Error: `You are not a member of ${room.name}` }) } else { res.status(200).json(room) } } }) } ) router.get( '/', passport.authenticate('jwt', { session: false }), (req, res) => { Room.find() .sort({ createdDate: -1 }) .then(rooms => { let joinedRooms = [] rooms.forEach(element => { if (element.members.includes(req.user._id)) { joinedRooms.push(element) } }) if (joinedRooms.length === 0) { res.status(400).json({ Error: "You don't have any rooms" }) } else { res.status(200).json(joinedRooms) } }) } ) module.exports = router <file_sep>/client/src/router/index.js import Vue from 'vue' import VueRouter from 'vue-router' import Login from '../views/Login.vue' import Register from '../views/Register.vue' import Dashboard from '../views/Dashboard.vue' import Room from '../views/Room.vue' import User from '../views/User.vue' import CreateRoom from '../views/CreateRoom' Vue.use(VueRouter) const routes = [ { path: '/dashboard', name: 'Dashboard', component: Dashboard }, { path: '/login', name: 'Login', component: Login }, { path: '/register', name: 'Register', component: Register }, { path: '/room/:room_id', name: 'Room', component: Room }, { path: '/user/:user_id', name: 'User', component: User }, { path: '/create-room', name: 'CreateRoom', component: CreateRoom } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router <file_sep>/index.js const express = require('express') var cors = require('cors') const app = express() const http = require('http') const socketIo = require('socket.io') const port = process.env.PORT || 3000 const mongoose = require('mongoose') const keys = require('./config/keys') const bodyParser = require('body-parser') const passport = require('passport') const serveStatic = require('serve-static') app.use( cors({ origin: '*' }) ) app.use(bodyParser.urlencoded({ extended: false })) app.use(bodyParser.json()) const users = require('./api/user/UserApi') const rooms = require('./api/room/RoomApi') app.use('/api/user', users) app.use('/api/room', rooms) mongoose .connect(keys.keys.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { console.log('Database connected') }) .catch(err => { console.log(err) }) app.use(passport.initialize()) require('./config/passport')(passport) app.get('/chat', (req, res) => res.send('')) const server = http.Server(app) server.listen(port, () => console.log(`Example app listening on port ${port}!`)) app.use(serveStatic(__dirname + '/client/dist')) <file_sep>/readme.md # [M](https://www.mongodb.com/)[e](https://expressjs.com/)[v](https://vuejs.org/)[n](https://nodejs.org/en/) Chat with [socket.io](https://socket.io/) ## Description Chat application with rooms built with: - [MongoDB](https://www.mongodb.com/) - [Express](https://expressjs.com/) - [Vue](https://vuejs.org/) - [Node.js](https://nodejs.org/en/) - [socket.io](https://socket.io/) ## Setup 1. Clone the project, edit the keys.js.example file and delete 2. the .example part. 3. Run npm i 4. Run node index.js So far... ## TODO - ~~Database connection~~ - ~~Models for Users, rooms~~ - ~~Encrypt password~~ - ~~Endpoint for login with encrypted pw and give a session back~~ - ~~Endpoint for register with encrypted pw~~ - ~~Endpoint for user creation~~ - Server side validation - Validate data on the ui - Add the token to every request and add the user to store - Populate users to rooms - Add every request to one file - Display that your are not authenticated to view this page - ~~User can join twice to any room~~ - Ask twice for passwords, on the UI and check them to be the same in the backend also - Delete and update for users - ~~Endpoint for room creation~~ - ~~Delete and edit room~~ - Add [socket.io](https://socket.io/) backend part - The whole frontend with vue and [socket.io](https://socket.io/) - Add logger instead of console.log and throw err - Display members of the room ### Notes for me - ~~Do I need this '/create-room', '/delete-room' paths? Method should be enough~~ Nope - Roles would be nice to have for the rooms - Check the .populate part, I think we will need it later <file_sep>/api/user/UserApi.js const express = require('express') const router = express.Router() const bcrypt = require('bcrypt') const jwt = require('jsonwebtoken') const keys = require('../../config/keys') const passport = require('passport') const User = require('../../models/User') router.get('/test', (req, res) => res.json({ msg: 'Users works' }) ) // Find user by id router.get('/:user_id', (req, res) => { User.findById(req.param.user_id) .populate('user', ['email', 'displayName', 'avatar', 'createdDate']) .then(user => { if (!user) { res.status(404).json('User not found') } else { res.json(user) } }) .catch(err => { res.status(404).json({ msg: 'User not found' }) }) }) // Register user router.post('/register', (req, res) => { User.findOne({ email: req.body.email }).then(user => { if (user) { res.status(400).json({ msg: 'Email address already taken' }) } else { bcrypt.genSalt(10, (err, salt) => { bcrypt.hash(req.body.password, salt, (err, hash) => { if (err) { throw err } else { newUser = new User({ email: req.body.email, displayName: req.body.displayName, avatar: req.body.avatar, password: <PASSWORD> }) newUser .save() .then(user => { res.status(201).json({ msg: `${user.displayName} register` }) }) .catch(err => res.json(err)) } }) }) } }) }) router.post('/login', (req, res) => { User.findOne({ email: req.body.email }).then(user => { if (!user) { res.status(400).json('Wrong email or password') } else { bcrypt.compare(req.body.password, user.password, (err, result) => { if (err) { res.status(400).json('Wrong email or password') } else { const payLoad = { id: user.id, displayName: user.displayName, avatar: user.avatar } jwt.sign( payLoad, keys.keys.secretOrKey, { expiresIn: 3600 }, (err, token) => { if (err) { res.json(err) } else { res.status(200).json({ success: true, token: 'Bearer ' + token }) } } ) } }) } }) }) module.exports = router <file_sep>/client/src/store/index.js import Vue from 'vue' import Vuex from 'vuex' import setAuthToken from '../utils/setAuthToken' import jwt from 'jwt-decode' Vue.use(Vuex) export default new Vuex.Store({ state: { isAuthenticated: false, user: null }, mutations: { loggedin(state, token) { localStorage.setItem('jwtToken', token.token) setAuthToken(token.token) //Set isAuthenticated to true in the store //deocec value should be the user, save it in the store const decoded = jwt(token.token) state.user = decoded state.isAuthenticated = !this.isAuthenticated } }, actions: {}, modules: {} }) <file_sep>/models/Message.js var mongoose = require('mongoose') var Schema = mongoose.Schema var MessageSchema = new Schema({ text: { type: String, required: true }, room: { type: Schema.type.Room }, messages: { type: [String] }, createdDate: { type: Date, default: Date.now }, createdBy: { type: Schema.type.User, required: true } }) module.exports = Message = mongoose.model('rooms', MessageSchema) <file_sep>/client/dist/precache-manifest.cbb680f3d1498a6faeaa2ec89f4f0297.js self.__precacheManifest = (self.__precacheManifest || []).concat([ { "revision": "c0c27dc94410943c59ce", "url": "/css/app.bc0cfbef.css" }, { "revision": "9c8ebe9ea8b94023869aeea0d2f8c8a3", "url": "/index.html" }, { "revision": "c0c27dc94410943c59ce", "url": "/js/app.064b14c0.js" }, { "revision": "ec3f54c53d2ac71108ef", "url": "/js/chunk-vendors.e01929be.js" }, { "revision": "e07dad9ca2f04ffa40a80acc420415d7", "url": "/manifest.json" }, { "revision": "735ab4f94fbcd57074377afca324c813", "url": "/robots.txt" } ]);<file_sep>/models/Room.js var mongoose = require('mongoose') var Schema = mongoose.Schema var RoomSchema = new Schema({ name: { type: String, required: true }, members: { type: [Schema.Types.ObjectId], ref: 'users' }, avatar: { type: String }, createdDate: { type: Date, default: Date.now }, createdBy: { type: Schema.Types.ObjectId, ref: 'users', required: true } }) module.exports = Room = mongoose.model('rooms', RoomSchema)
5a3d663f673c8728ceef838cd2bafd814f43769a
[ "JavaScript", "Markdown" ]
9
JavaScript
NorbertCseh/mevn-chat
1ce6d84cf2806c75bdf5efbbd5b69586da08baae
3ff19847af041a328f866eb98e1bb28aa34edeab
refs/heads/master
<file_sep>import {Pipe, PipeTransform} from '@angular/core'; @Pipe({ name: 'search' }) export class SearchPipe implements PipeTransform { public transform(value: any[], keys: [], term: string) { if (!term) return value; return (value || []) .filter(item => keys .some(key => item[key].toLowerCase().indexOf(term.toLowerCase()) !== -1) ); } }<file_sep>import {Pipe, PipeTransform} from '@angular/core'; @Pipe({ name: 'sorting' }) export class SortingPipe implements PipeTransform { public transform(value: any[], keys: string) { if (!keys) return value; return value.sort((a: any, b: any) => { if(a[keys] < b[keys]) { return -1; } else if (a[keys] > b[keys]) { return 1; } else { return 0; } }); } }<file_sep>import { Component, OnInit } from '@angular/core'; import { HttpService } from '../../services/http.service'; import { Title } from '@angular/platform-browser'; import {Inspection} from '../../inspection'; @Component({ selector: 'inspection-comp', styleUrls: ['./app.sass',], templateUrl: './app.html', }) export class AppComponent implements OnInit { title= 'Инспекция по ресторанам'; inspectionList: []; inspectionHead= [ {"title": "Наименование","code": "business_name", "checked": false}, {"title": "Адрес","code": "business_address", "checked": false}, {"title": "Город","code": "business_city", "checked": false}, {"title": "Номер","code": "business_phone_number", "checked": false}, {"title": "Индекс","code": "business_postal_code", "checked": false}, {"title": "Дата","code": "inspection_date", "checked": false}, {"title": "Статус","code": "inspection_description", "checked": false}, {"title": "Тип","code": "inspection_type", "checked": false}, ]; optionsChecked= [ "business_name", "business_address", "business_city", "business_phone_number", "business_postal_code", "inspection_date", "inspection_description", "inspection_type" ]; position: number; sortingKey: string; constructor(private httpService: HttpService, private titleService: Title){} public setTitle( newTitle: string) { this.titleService.setTitle(this.title); } ngOnInit() { this.httpService.getData() .subscribe((resp: []) => { this.inspectionList= resp; }); } sorting(key: string) { this.sortingKey = key; } updateCheckedOptions(option: string, event: any) { if (!event.target.checked) { this.optionsChecked.push(option); } else { this.position = this.optionsChecked.indexOf(option); this.optionsChecked.splice(this.position, 1); } } } <file_sep>import { Directive, ElementRef, Renderer2, AfterContentInit, Input } from '@angular/core'; @Directive ({ selector: '[status]' }) export class StatusDirective implements AfterContentInit { @Input() inspectionDesc = ""; constructor( private elementRef: ElementRef, private renderer: Renderer2 ) { } ngAfterContentInit() { switch (this.inspectionDesc) { case "REINSPECTION REQUIRED": this.renderer.addClass(this.elementRef.nativeElement, 'red'); break; case "SHORTER DATE ADVANCE": this.renderer.addClass(this.elementRef.nativeElement, 'orange'); break; case "NO ACTION": this.renderer.addClass(this.elementRef.nativeElement, 'green'); break; case "ISSUED PERMIT": this.renderer.addClass(this.elementRef.nativeElement, 'blue'); break; default: break; } } }<file_sep>import { NgModule } from '@angular/core'; import { BrowserModule, Title } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; import { HttpService } from './services/http.service'; import { StatusDirective } from './directives/status.directive'; import { SearchPipe } from './pipes/search.pipe'; import { SortingPipe } from './pipes/sorting.pipe'; import { AppComponent } from './components/main/app.component'; @NgModule({ imports: [ BrowserModule, FormsModule, HttpClientModule, ], declarations: [ AppComponent, StatusDirective, SearchPipe, SortingPipe ], bootstrap: [ AppComponent ], providers: [ Title, HttpService ], }) export class AppModule { } <file_sep>export class Inspection{ id: object; business_id: string; business_name: string; business_address: string; business_city: string; business_state: string; business_postal_code: string; business_phone_number: string; inspection_date: string; inspection_score: string; inspection_description: string; inspection_type: string; violation_description: string; violation_code: string; business_location: string; }
a45f83ae8f345d7876d3b87579b4b3d6da1f04f2
[ "TypeScript" ]
6
TypeScript
bakhtiyarov-r/OpCodeTest
31f20a45116b8a7049cac1b99fac34a23f354bca
0fe57888f47b82de8143ea4551e11476aac9d548
refs/heads/master
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package software_fundamental; /** * * @author khanh */ public class pillbox_73194 { /** * @param args the command line arguments */ public static void main(String[] args) { char [] pillbox = new char[7]; pillbox[0] = 'D'; pillbox[1] = 'r'; pillbox[2] = '.'; pillbox[3] = 'J'; pillbox[4] = 'a'; pillbox[5] = 'v'; pillbox[6] = 'a'; char [] pillbox1 = {'w','e','e','k','e','n','d'}; for (int i = pillbox.length - 1; i >=0; i--){ System.out.print(pillbox[i]); } System.out.println(); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package software_fundamental; /** * * @author khanh */ public class student_73194 { private int studId; private String studName; private String program; private String course; private String demo public student_73194() { } public student_73194(int studId, String studName) { this.studId = studId; this.studName = studName; } public int getStudId() { return studId; } public void setStudId(int studId) { this.studId = studId; } public String getStudName() { return studName; } public void setStudName(String studName) { this.studName = studName; } public String getProgram() { return program; } public void setProgram(String program) { this.program = program; } public static void main(String[] args) { student_73194 s1 = new student_73194(); student_73194 s2 = new student_73194(2, "Hamza"); student_73194 [] studentList = new student_73194[5]; studentList[0] = s1; studentList[1] = s2; for (int i = 0; i < studentList.length; i++){ System.out.println("student name: " + studentList[i].getStudName()); System.out.println("student id " + studentList[i].getStudId()); } } }
bfe50675cb63b8f05259d70420429f9b767c9c6f
[ "Java" ]
2
Java
hamzsajjad150/student_demo
b77e2b0f4fc8e4dc972009c39431aba68d85096f
8c5321891d9bb009219b4d7e590c6bbfb5fcff47
refs/heads/master
<file_sep><?php get_header(); ?> <div class="cover"> <div class="cover-image"> <div class="masthead"><NAME></div> </div> </div> <?php $dir = "partials/"; $partials = array( "news", "music", "videos", "featured", "photos", "events", "munz-mind" ); foreach ( $partials as $partial ) { get_template_part( $dir . $partial ); } ?> <?php get_footer(); ?> <file_sep><div class="music"> <div class="container"> <div class="row"> <h1>music</h1> </div> <?php $args = array( "post_type" => array( "music" ), "orderby" => "date" ); $albums = new WP_Query ( $args ); $index = 0; while ( $albums->have_posts() ) : $albums->the_post(); ?> <div class="album"> <a class="permalink" href="<?php the_field( "outgoing_url" ); ?>" target="_blank"> <?php the_post_thumbnail( "music-thumb" ); ?> </a> <?php the_title( "<div class='title'>", "</div>" ); ?> <div class="excerpt"><?php the_excerpt(); ?></div> <a class="permalink" href="<?php the_field( "outgoing_url" ); ?>" target="_blank">listen</a> </div> <?php $index++; if ( $index % 3 === 0 ) : ?><div class="clearfix"></div><?php endif; ?> <?php endwhile; wp_reset_postdata(); ?> </div> </div> <file_sep> <?php if(!is_single()):?> <footer> <h1>Follow Damien</h1> <?php wp_nav_menu( array( "theme_location" => "social", "container" => false ) ); ?> </footer> <?php endif; ?> <!-- Javcascript --> <?php wp_footer(); ?> </body> </html> <file_sep><?php class InstagramApi { private $data = array ( "response" => null, "next_page" => null, "photos" => array() ); private $request = "https://api.instagram.com/v1/users/26970451/media/recent/?client_id="; private $params = array ( "key" => null ); public function __construct( $key ) { $this->params["key"] = $key; $this->api_request(); } private function api_request( $request = null ) { if ( is_null( $request ) ) { $request = $this->request; $request .= $this->params["key"]; } $body = wp_remote_retrieve_body( wp_remote_get( $request, array( "timeout" => 18, "content-type" => "application/json" ) ) ); try { $response = json_decode( $body, true ); $this->data["response"] = $response["data"]; $this->data["next_page"] = $response["pagination"]["next_url"]; $this->setup_data( $this->data ); while ( count( $this->data["photos"] ) < 160 ) { $this-> api_request( $this->data["next_page"] ); } } catch ( Exception $ex ) { $this->data = null; } } private function setup_data( $data ) { foreach ( $data["response"] as $obj ) { $images = $obj["images"]; $new_obj = array( "id" => $obj["id"], "type" => $obj["type"], "large_img" => $images["standard_resolution"]["url"], "small_img" => $images["low_resolution"]["url"], "thumb_img" => $images["thumbnail"]["url"] ); if ( $obj["type"] === "video" ) { $videos = $obj["videos"]; $new_obj["large_mp4"] = $videos["standard_resolution"]["url"]; $new_obj["small_mp4"] = $videos["low_resolution"]["url"]; } array_push( $this->data["photos"], $new_obj ); } } public function query_photos() { $output = json_encode( $this->data["photos"] ); return $output; } public function pagination_query() { $this->data["photos"] = array(); $this->api_request( $this->data["next_page"] ); $output = json_encode( $this->data["photos"] ); return $output; } } ?> <file_sep><div class="news"> <div class="container"> <div class="row"> <h1>news</h1> </div> <div class="row"> <?php $index = 0; ?> <?php while ( have_posts() ) : the_post(); ?> <?php $if_recent = ( $index < 3 ); $image_size = ( $if_recent ? "news-feat-thumb" : "news-thumb" ); $post_class = ( $if_recent ? "recent-post" : "prev-post" ); ?> <div class="<?php echo $post_class; ?>"> <?php the_post_thumbnail( $image_size ); ?> <?php the_title("<div class='title'>", "</div>"); ?> <div class="excerpt"><?php the_excerpt(); ?></div> <a class="permalink" href="<?php the_permalink(); ?>">read now</a> </div> <?php $index++; ?> <?php if ( $index === 3 ) : ?><div class="end-recent"></div><?php endif; ?> <?php endwhile; wp_reset_postdata(); ?> </div> </div> </div> <file_sep><?php include_once "api/keys.php"; include_once "api/instagram.php"; include_once "api/youtube.php"; $instagram = new InstagramApi( $keys["instagram"] ); $youtube = new YouTubeApi( $keys["youtube"] ); add_theme_support( "post-thumbnails" ); add_image_size( "music-thumb", 350, 348, true ); add_image_size( "news-thumb", 350, 360, true ); add_image_size( "news-feat-thumb", 540, 540, true ); add_image_size( "post-pagination-thumb", 48, 48, true ); add_filter( "excerpt_length", "custom_excerpt_length", 999 ); function custom_excerpt_length( $length ) { return 12; } add_filter( "excerpt_more", "new_excerpt_more" ); function new_excerpt_more( $more ) { return "..."; } remove_filter( "the_excerpt", "wpautop" ); register_nav_menus( array( "social" => __( "Social Media Menu", "damien-palace" ) ) ); add_action( "wp_enqueue_scripts", "enqueue_assets" ); function enqueue_assets() { $temp_dir = get_template_directory_uri(); $bower_dir = "${temp_dir}/bower_components"; $css_dir = "${temp_dir}/assets/css"; $js_dir = "${temp_dir}/assets/js"; $fancybox = "${bower_dir}/fancybox/source"; $fit_text = "${bower_dir}/FitText.js"; $mustache = "${bower_dir}/mustache"; // css wp_enqueue_style( "my-stylesheet", "${css_dir}/my.css" ); wp_enqueue_style( "fancybox-css", "${fancybox}/jquery.fancybox.css" ); // javascript wp_enqueue_script( "my-js", "${js_dir}/my.js", array( "jquery" ), false, true ); wp_enqueue_script( "fancybox-js", "${fancybox}/jquery.fancybox.pack.js", array( "jquery" ), false, true ); wp_enqueue_script( "fancybox-media", "${fancybox}/helpers/jquery.fancybox-media.js", array( "fancybox-js" ), false, true ); wp_enqueue_script( "fit-text", "${fit_text}/jquery.fittext.js", array( "my-js" ), false, true ); wp_enqueue_script( "mustache", "${mustache}/mustache.js", array( "my-js" ), false, true ); // ajax url wp_localize_script( "my-js", "wp_urls", array( "ajax_url" => admin_url( "admin-ajax.php" ), "template_url" => $temp_dir ) ); } add_action( "init", "enqueue_post_types" ); function enqueue_post_types() { $labels = array( "name" => "Music", "singular_name" => "Music", "menu_name" => "Music", "name_admin_bar" => "Music", "add_new" => "Add New Album", "add_new_item" => "Add New Album", "new_item" => "New Album", "edit_item" => "Edit Album", "view_item" => "View Album", "all_items" => "All Albums", "parent_item_colon" => "Parent Album:", "not_found" => "No albums found.", "not_found_in_trash" => "No albums found in Trash." ); $args = array( "labels" => $labels, "public" => true, "publicly_queryable" => true, "show_ui" => true, "show_in_nav_menus" => false, "menu_position" => 5, "menu_icon" => "dashicons-format-audio", "query_var" => true, "rewrite" => array( "slug" => "music" ), "capability_type" => "post", "has_archive" => false, "supports" => array( "title", "thumbnail", "excerpt" ) ); register_post_type( "music", $args ); $labels = array( "name" => "Events", "singular_name" => "Event", "menu_name" => "Events", "name_admin_bar" => "Event", "add_new" => "Add New Event", "add_new_item" => "Add New Event", "new_item" => "New Event", "edit_item" => "Edit Event", "view_item" => "View Event", "all_items" => "All Events", "parent_item_colon" => "Parent Events:", "not_found" => "No events found.", "not_found_in_trash" => "No events found in Trash." ); $args = array( "labels" => $labels, "public" => true, "publicly_queryable" => true, "show_ui" => true, "show_in_nav_menus" => false, "menu_position" => 5, "menu_icon" => "dashicons-calendar-alt", "query_var" => true, "rewrite" => array( "slug" => "events" ), "capability_type" => "post", "has_archive" => false, "supports" => array( "title" ) ); register_post_type( "events", $args ); flush_rewrite_rules(); } add_action( "admin_init", "remove_submenu_pages", 999 ); function remove_submenu_pages() { $subpages = array( "themes.php", "theme-editor.php" ); foreach ( $subpages as $subpage ) { remove_submenu_page( "themes.php", $subpage ); } global $submenu; unset( $submenu["themes.php"][6] ); } add_action( "admin_menu", "remove_menu_pages" ); function remove_menu_pages() { $menu = array( "upload.php", "edit.php?post_type=page", "edit-comments.php", "plugins.php", "users.php", "tools.php", "options-general.php", "link-manager.php" ); foreach ( $menu as $page ) { remove_menu_page( $page ); } remove_menu_page( "themes.php" ); add_action( "admin_menu", "remove_acf_menu", 999 ); function remove_acf_menu() { $admins = array( "webdev" ); $current_user = wp_get_current_user(); if ( !in_array( $current_user->user_login, $admins ) ) { remove_menu_page( "edit.php?post_type=acf" ); } } }; add_action( "wp_ajax_nopriv_query_photos", "my_photo_query" ); add_action( "wp_ajax_query_photos", "my_photo_query" ); function my_photo_query() { global $instagram; $data = $instagram->query_photos(); echo $data; wp_die(); } add_action( "wp_ajax_nopriv_query_pagination", "my_pagination_query" ); add_action( "wp_ajax_query_pagination", "my_pagination_query" ); function my_pagination_query() { global $instagram; $data = $instagram->pagination_query(); echo $data; wp_die(); } add_action( "wp_ajax_nopriv_query_videos", "my_video_query" ); add_action( "wp_ajax_query_videos", "my_video_query" ); function my_video_query() { global $youtube; $data = $youtube->query_videos(); echo $data; wp_die(); } ?> <file_sep><?php get_header(); ?> <?php while ( have_posts() ) : the_post(); ?> <div id="post-<?php the_ID(); ?>" <?php post_class("container"); ?>> <div class="row"> <div class="logo"><NAME></div> </div> <div class="row"> <figure> <?php the_post_thumbnail(); ?> </figure> </div> <div class="row"> <aside> <h1><?php the_time( "M j" ); ?></h1> </aside> <section class="content"> <h1><?php the_title(); ?></h1> <?php the_content(); ?> </section> </div> <div class="row"> <?php $prev_post = get_previous_post(); $next_post = get_next_post(); ?> <div id="adjacent-posts"> <div class="row"> <div class="prev"> <?php if( !empty( $prev_post ) ): ?> <?php echo get_the_post_thumbnail( $prev_post->ID, "post-pagination-thumb" ); ?> <a href="<?php echo get_permalink( $prev_post->ID ); ?>"> <span>prev post</span> <?php echo $prev_post->post_title; ?> </a> <?php endif; ?> </div> <div class="next"> <?php if( !empty( $next_post ) ): ?> <?php echo get_the_post_thumbnail( $next_post->ID, "post-pagination-thumb" ); ?> <a href="<?php echo get_permalink( $next_post->ID ); ?>"> <span>next post</span> <?php echo $next_post->post_title; ?> </a> <?php endif; ?> </div> </div> </div> </div> <div class="row"> <section id="comment-section"> <?php comments_template(); ?> </section> </div> </div> <?php endwhile; ?> <?php get_footer(); ?> <file_sep><div class="events"> <div class="container"> <div class="row"> <h1>events</h1> </div> <?php $args = array( "post_type" => array( "events" ), "orderby" => "date" ); $slides = new WP_Query ( $args ); while ( $slides->have_posts() ) : $slides->the_post(); ?> <div class="event"> <div class="date"><?php the_field( "event_date" ); ?></div> <div class="venue"> <div class="name"> <?php the_field( "event_venue" ); ?> </div> <div class="locale"> <?php the_field( "event_location" ); ?> </div> </div> <div class="link"> <a href="<?php the_field( "event_url" ); ?>" target="_blank">go</a> </div> </div> <?php endwhile; wp_reset_postdata(); ?> </div> </div> <file_sep><?php class YouTubeApi { private $request = "https://www.googleapis.com/youtube/v3/playlistItems"; private $params = array( "key" => null, "maxResults" => 30, "part" => "snippet", "playlistId" => array ( "featured" => "PLx01nh2XnVSV1r7ogt5KLEoY8l9-cwJO6", "official" => "PLx01nh2XnVSX1L2gZV4Xe_41ceA9ZTBY4", "munzmind" => "PLx01nh2XnVSWwq4mvO7IoegXKote5dA1L" ) ); private $data = array ( "response" => array ( "featured" => array(), "official" => array(), "munzmind" => array() ), "videos" => array ( "featured" => array(), "official" => array(), "munzmind" => array() ) ); public function __construct( $key ) { $this->params["key"] = $key; $this->api_request(); } private function compile_request() { $endpoint = $this->request; $params = $this->params; $output; reset( $params ); $first = key( $params ); foreach ( $params as $key => $val ) { if ( $key === "playlistId" ) { foreach ( $params[$key] as $key => $val ) { $value = $endpoint . "&playlistId=${val}"; $output[$key] = $value; } break; } $prefix = $key === $first ? "?" : "&"; $endpoint .= "${prefix}${key}=${val}"; } return $output; } private function api_request() { $resources = $this->compile_request(); foreach ( $resources as $key => $request ) { $res = wp_remote_get( $request, array( "timeout" => 10 ) ); $body = wp_remote_retrieve_body( $res ); try { $response = json_decode( $body, true ); $this->data["response"][$key] = $response["items"]; $this->setup_data( $this->data, $key ); } catch ( Exception $ex ) { $this->data["response"][$key] = null; } } } private function setup_data( $data, $key ) { foreach ( $data["response"][$key] as $obj ) { $resObj = $obj["snippet"]; $images = $resObj["thumbnails"]; $videoId = $resObj["resourceId"]["videoId"]; $new_obj = array( "id" => $videoId, "default_img" => $images["default"]["url"], "medium_img" => $images["medium"]["url"], "high_img" => $images["high"]["url"] ); if ( isset( $images["standard"] ) ) { $new_obj["standard_img"] = $images["standard"]["url"]; } array_push( $this->data["videos"][$key], $new_obj ); } } public function query_videos() { $output = json_encode( $this->data["videos"] ); return $output; } } ?> <file_sep>jQuery(function($) { var fetchMedia = function(media) { return $.ajax({ dataType: "json", data: { action: "query_" + media }, type: "post", url: wp_urls.ajax_url }); }, fetchView = function(className) { return $(className).find(".media"); }, fetchPartial = function(partialName) { var dir = wp_urls.template_url + "/assets/js/partials/", partial = dir + partialName; return partial; }, setupView = function(obj) { var $view = obj.view, $viewParent = $view.parent(), btnExists = $viewParent.find(".paginate-btn").length, btn = "<div class=\"paginate-btn\"><div>View More</div></div>"; var media = obj.data, part = obj.partial, sliceEnd = media.length > 8 ? 8 : media.length; $.get(fetchPartial(part), function(template) { if (media.length > 8 && !btnExists) { $viewParent.append(btn); } $.each(media.slice(0, sliceEnd), function(idx, obj) { var rendered = Mustache.render(template, obj); $view.append(rendered); media.shift(0, 1); if (~part.indexOf("featured")) { return false; } }); }); }; var data = {}, view = { photo: fetchView(".photos"), video: { featured: fetchView(".featured"), official: fetchView(".videos"), munzmind: fetchView(".munz-mind") } }, setupParams; var requests = [ fetchMedia("photos"), fetchMedia("videos") ]; $.when.apply($, requests).then(function(photos, videos) { data = { photo: photos[0], video: videos[0] }, setupParams = [{ partial: "photos.mst", view: view.photo, data: data.photo }, { partial: "featured.mst", view: view.video.featured, data: data.video.featured }, { partial: "official.mst", view: view.video.official, data: data.video.official }, { partial: "munzmind.mst", view: view.video.munzmind, data: data.video.munzmind }]; $.each(setupParams, function(idx, params) { setupView(params); }); }); $.fn.pagination = function() { $(document).on("click", ".paginate-btn", function() { $parents = $(this).parents(); if ($parents.hasClass("photos")) { if (data.photo.length > 0) { setupView(setupParams[0]); } else { fetchMedia("pagination").then(function(more) { setupParams[0].data = data.photo = more; setupView(setupParams[0]); }); } } else { } }); }; $(".paginate-btn").pagination(); }); jQuery(function($) { // fancybox $(".fancybox").fancybox({ helpers: { media: { youtube: { params: { autoplay: 1, controls: 0, showinfo: 0 } } } }, padding: 0 }); // fitText $(".cover").find(".cover-image > .masthead").fitText(); });
84ac50e8f24c3d3d67684069d0a06cdd1e800bc9
[ "JavaScript", "PHP" ]
10
PHP
iamricky/damien-palace
668f359ea1e6d589843746f19b4a4585ff9a68dd
846dea4f0866cbe3db37062582acc7a7306b88c1
refs/heads/master
<file_sep>### @export "import-the-library" import pyalm.pyalm as alm ### @export "get-single-doi" article = alm.get_alm("10.1371/journal.pone.0029797", info="summary") ### @export "print-article" article ### @export "print-biblio" article.title article.url ### @export "print-ids" article.doi article.pmid ### @export "print-stats" article.views article.citations ### @export "multiple-dois" articles = alm.get_alm( ["10.1371/journal.pone.0029797","10.1371/journal.pone.0029798"], info="summary") len(articles) for article in articles: print article.title,"DOI:", article.doi, print "Views:", article.views ### @export "get-event-level-cites" article = alm.get_alm("10.1371/journal.pone.0029797", info="event", source="crossref") article.sources['crossref'] ### @export "print-cites-metrics" article.sources['crossref'].metrics.total article.sources['crossref'].metrics.citations article.sources['crossref'].metrics.shares == None ### @export "source-cites-attributes" article.sources['crossref'].name article.sources['crossref'].display_name article.sources['crossref'].events_url article.sources['crossref'].update_date ### @export "print-cites-events" article.sources['crossref'].events[0] ### @export "get-history-level-cites" article = alm.get_alm("10.1371/journal.pone.0029797", info="history", source="crossref") len(article.sources['crossref'].histories) article.sources['crossref'].histories[-1] <file_sep>import datetime import time import requests import pyalm.config BASE_HEADERS = {'Accept':'application/json'} SEARCH_URL = 'http://api.plos.org/search?q=' ''' _JMap - map a journal name to a url. ''' _JMap = { 'PLoS Biology' : 'http://www.plosbiology.org', 'PLoS Genetics' : 'http://www.plosgenetics.org', 'PLoS Computational Biology' : 'http://www.ploscompbiol.org', 'PLoS Medicine' : 'http://www.plosmedicine.org', 'PLoS ONE' : 'http://www.plosone.org', 'PLoS Neglected Tropical Diseases' : 'http://www.plosntds.org', 'PLoS Clinical Trials' : 'http://clinicaltrials.ploshubs.org', 'PLoS Pathogens' : 'http://www.plospathogens.org' } ''' _JIds - map a 4 character journal id to quoted journal name. ''' _JIds = { 'pbio' : '"PLoS Biology"', 'pgen' : '"PLoS Genetics"', 'pcbi' : '"PLoS Computational Biology"', 'pmed' : '"PLoS Medicine"', 'pone' : '"PLoS ONE"', 'pntd' : '"PLoS Neglected Tropical Diseases"', 'pctr' : '"PLoS Clinical Trials"', 'ppat' : '"PLoS Pathogens"' } def articleUrl(doi,jid): ''' articleUrl- return a valid link to the article page given the journal 4 character identifier and the article doi. ''' return _JMap[jid] + '/article/' + quote('info:doi/' + doi) def articleXML(doi,jid): ''' articleXML - return a valid link to the article XML give the journal 4 character identifier and the article doi. ''' return _JMap[jid] + '/article/fetchObjectAttachment.action?uri=' + quote('info:doi/' + doi) +\ '&representation=XML' class Request: """ Base class for a PLOS Search API Request Object """ def __init__(self, query = None, fields = None, instance = 'plos', start=0, limit=99, maxRows=100, verbose=False, delay = 0.5): if query is None: self.query = {} else: self.query = query if fields is None: self.fields = ['doi'] else: self.fields = fields self.start = start self.limit = limit self.maxrows = limit if limit < maxRows else maxRows self.delay = delay self.instance = instance self.api_key = pyalm.config.APIS.get(self.instance).get('key') self._query_text = '' self._api_url = SEARCH_URL self._headers = BASE_HEADERS self._params = { 'start': str(self.start), 'rows': str(self.maxrows), 'fq': 'doc_type:full AND !article_type_facet:"Issue Image"', 'wt': 'json', 'api_key' : self.api_key } def add_query_term(self, term, query): self.query[term] = query def search_date(self, start, end=None): """ Add date limits to the query The function accepts datetime objects, year integers, year strings, or YYYY-mm strings. If end is not set then assumes the current date. Single years will default to first of January so to search for 2012 articles start=2012 and end=2013 """ start_date = self._process_dates(start) if end: end_date = self._process_dates(end) else: end_date = datetime.datetime.now().isoformat() self.query['publication_date'] = '[%sZ TO %sZ]' % (start_date, end_date) def search_year(self, year): """ Add date limits to the query for a single year The function accepts either strings or ints that can be parsed to the year element of datetime objects. """ start_date = datetime.datetime(int(year), 1, 1, 0, 0, 0) end_date = datetime.datetime(int(year), 12, 31, 23, 59, 59) self.search_date(start_date, end_date) def _process_dates(self, date): """ Utility method for handling dates as date, datetime, or strings """ try: string = date.isoformat() return string except AttributeError: # If date is not a datetime object year = int(str(date).split('-')[0]) try: month = int(str(date).split('-')[1]) try: day = int(str(date).split('-')[2]) except IndexError: day = 1 except IndexError: # No month in the string month = 1 day = 1 return datetime.datetime(year, month, day, 0,0,0).isoformat() def add_field(self, field): self.fields.append(field) def set_query_text(self, text): self._query_text = text def _format_query(self): try: _query_text = '' _query_text = ' AND '.join(['%s:%s' % (k,v) for k,v in self.query.iteritems()]) self._query_text = _query_text return _query_text except AttributeError: assert type(self.query) == str self._query_text = self.query return self._query_text def _format_query_url(self): query_url = self._api_url + self._format_query() return query_url def _finalize_params(self): self._params['fl'] = ','.join(self.fields) return self._params def get(self): query_url = self._format_query_url() params = self._finalize_params() headers = self._headers response = requests.get(query_url, params = params, headers = headers ) response.raise_for_status() return_json = response.json() self.response = response numFound = response.json().get('response').get('numFound') start = self.start + self.maxrows while len(return_json.get('response').get('docs')) < numFound: self._params['start'] = start params = self._finalize_params() paged_response = requests.get(query_url, params = params, headers = headers ) response.raise_for_status() return_json.get('response').get('docs').extend(paged_response.json().get('response').get('docs')) time.sleep(self.delay) start += self.maxrows return return_json def collect_dois(query, dates=None): request = Request(query) if dates: try: request.search_date(dates[0],dates[1]) except TypeError: request.search_date(dates) resp = request.get() dois = [article.get('doi')[0] for article in resp.get('response').get('docs')] return dois <file_sep>import unittest import pyalm.pyalm as pyalm import pyalm.events as events import datetime import pprint import json from test_pyalm import TestOffline as TestOffline class TestSourcesEvents(TestOffline): def testTwitterEvents(self): tweets = [] for tweet in self.mock_resp.sources['twitter'].events: tweets.append(events.Tweet(tweet)) self.assertEqual(tweets[0].username, 'opdebult') self.assertEqual(tweets[0].created_at, datetime.datetime(2012, 8, 19, 7, 26, 6)) self.assertEqual(tweets[0].id, '237088032224849920') self.assertEqual(tweets[0].profile_image, 'http://a0.twimg.com/profile_images/1741153180/Tidan_normal.jpg') self.assertEqual(tweets[0].text, "#PLOS: Ecological Guild Evolution and the Discovery of the World's Smallest Vertebrate http://t.co/yEGLyWTf") self.assertEqual(tweets[0].url, "http://twitter.com/opdebult/status/237088032224849920") self.assertEqual(tweets[8].username, 'didicikit') self.assertEqual(tweets[8].text, "Ecological Guild Evolution and the Discovery of the World's Smallest Vertebrate http://t.co/2G6fQJvFhq") self.assertEqual(tweets[8].url, "http://twitter.com/didicikit/status/313850610174799873") def testCrossrefEvents(self): cites = [] for cite in self.mock_resp.sources['crossref'].events: cites.append(events.Citation(cite)) #Testing against first entry self.assertEqual(cites[0].article_title, 'New insights into the systematics and molecular phylogeny of the Malagasy snake genus Liopholidophis suggest at least one rapid reversal of extreme sexual dimorphism in tail length') self.assertEqual(cites[0].doi, '10.1007/s13127-013-0152-4') self.assertEqual(cites[0].fl_count, 0) self.assertEqual(cites[0].issn, [u'1439-6092', u'1618-1077']) self.assertEqual(cites[0].journal_abbreviation, 'Org Divers Evol') self.assertEqual(cites[0].journal_title, 'Organisms Diversity & Evolution') self.assertEqual(cites[0].publication_type, 'full_text') self.assertEqual(cites[0].publication_year, 2013) self.assertEqual(cites[0].issue, None) self.assertEqual(cites[0].volume, None) self.assertEqual(cites[0].first_page, None) #Testing against last entry self.assertEqual(cites[6].article_title, 'Are diminutive turtles miniaturized? The ontogeny of plastron shape in emydine turtles') self.assertEqual(cites[6].doi, '10.1111/bij.12010') self.assertEqual(cites[6].fl_count, 0) self.assertEqual(cites[6].issn, '00244066') self.assertEqual(cites[6].journal_abbreviation, 'Biol J Linn Soc Lond') self.assertEqual(cites[6].journal_title, 'Biological Journal of the Linnean Society') self.assertEqual(cites[6].publication_type, 'full_text') self.assertEqual(cites[6].publication_year, 2013) self.assertEqual(cites[6].issue, 4) self.assertEqual(cites[6].volume, 108) self.assertEqual(cites[6].first_page, 727) #Contributors self.assertEqual(len(cites[0].contributors), 5) self.assertEqual(cites[0].contributors[0].contributor_role, 'author') self.assertEqual(cites[0].contributors[0].first_author, True) self.assertEqual(cites[0].contributors[0].given_name, 'Frank') self.assertEqual(cites[0].contributors[0].surname, 'Glaw') self.assertEqual(cites[0].contributors[0].sequence, 'first') self.assertEqual(cites[6].contributors[1].contributor_role, 'author') self.assertEqual(cites[6].contributors[1].first_author, False) self.assertEqual(cites[6].contributors[1].given_name, '<NAME>.') self.assertEqual(cites[6].contributors[1].surname, 'Feldman') self.assertEqual(cites[6].contributors[1].sequence, 'additional') def testWikipedia(self): wiki = events.WikiRef(self.mock_resp.sources['wikipedia'].events) self.assertEqual(wiki.ca, 2) self.assertEqual(wiki.commons, 0) self.assertEqual(wiki.cs, 0) self.assertEqual(wiki.en, 10) self.assertEqual(wiki.es, 2) self.assertEqual(wiki.fi, 1) self.assertEqual(wiki.fr, 3) self.assertEqual(wiki.hu, 0) self.assertEqual(wiki.it, 2) self.assertEqual(wiki.ja, 1) self.assertEqual(wiki.ko, 1) self.assertEqual(wiki.nl, 2) self.assertEqual(wiki.no, 2) self.assertEqual(wiki.pl, 7) self.assertEqual(wiki.pt, 2) self.assertEqual(wiki.ru, 3) self.assertEqual(wiki.sv, 1) self.assertEqual(wiki.total, 49) self.assertEqual(wiki.uk, 1) self.assertEqual(wiki.vi, 2) self.assertEqual(wiki.zh, 2) def testMendeley(self): mend = events.Mendeley(self.mock_resp.sources['mendeley'].events) self.assertEqual(mend.categories, [35, 48, 52, 43, 40, 44, 210]) self.assertEqual(mend.bookmarks, 50) self.assertEqual(mend.reader_countries, [ {u'name': u'United States', u'value': 18}, {u'name': u'Portugal', u'value': 8}, {u'name': u'Brazil', u'value': 8} ] ) self.assertEqual(mend.uuid, '476c0910-3e94-11e1-a0e9-0024e8453de6') self.assertEqual(mend.mendeley_url, 'http://www.mendeley.com/research/ecological-guild-evolution-discovery-worlds-smallest-vertebrate/') self.assertEqual(mend.file_url, 'https://api.mendeley.com/oapi/documents/file/476c0910-3e94-11e1-a0e9-0024e8453de6/164889e703e0cd991f1a6a5a77b469f74a546f9d/') def testFacebook(self): facebook = events.Facebook(self.mock_resp.sources['facebook'].events) self.assertEqual(facebook.commentsbox_count, 0) self.assertEqual(facebook.normalized_url, 'http://dx.doi.org/10.1371/journal.pone.0029797') self.assertEqual(facebook.click_count, 0) self.assertEqual(facebook.total_count, 228) self.assertEqual(facebook.comment_count, 22) self.assertEqual(facebook.like_count, 59) self.assertEqual(facebook.comments_fbid, None) self.assertEqual(facebook.share_count, 147) if __name__ == "__main__": unittest.main()<file_sep>from setuptools import setup setup(name='pyalm', version='0.1', description='Python Wrapper for the PLOS Article Level Metrics API', url='http://github.com/cameronneylon/pyalm', author='<NAME>', author_email='<EMAIL>', license='Apache', packages=['pyalm'], install_requires=['requests',], zip_safe=False)<file_sep>PyALM Docs ========== Contents -------- 1. Basic usage 1. Summary level information 2. More detailed source information 2. Working with data 1. Working with history 2. Working with events Basic usage ----------- ###Summary Level Information### After installation (see the README) import the library and call the API give a doi and the information level required (summary, event, history, detail). We are starting with the API call which just gives summary level information. {{ d['examples/example.py|idio|pycon|pyg']['import-the-library'] }} {{ d['examples/example.py|idio|pycon|pyg']['get-single-doi'] }} The returned object provides some basic information: {{ d['examples/example.py|idio|pycon|pyg']['print-article'] }} We can then start getting some summary information about the returned object. With the summary API call you obtain the basic bibliographic information (`title`, `doi`, `url`, `publication_date`), the most recent `update_date`, the identifiers for the paper (`doi`, `pmid`, `pmcid`) alongside summary metrics information (`views`, `shares`, `bookmarks`, `citations`). In each case the relevant information can be obtained as an attribute of the response: {{ d['examples/example.py|idio|pycon|pyg']['print-biblio'] }} {{ d['examples/example.py|idio|pycon|pyg']['print-ids'] }} {{ d['examples/example.py|idio|pycon|pyg']['print-stats'] }} The returned object is always a list of ArticleALM objects. If a single DOI is passed the list will be of length one. Multiple DOIs should be passed to the `get` method as a list of strings of the form `10.1371/journal.pgen.1004001`. {{ d['examples/example.py|idio|pycon|pyg']['multiple-dois'] }} ###More Detailed Source Information### To obtain more detailed information on each ALM source from the ALM API a request should be made for from detailed information. The options available are `event`, `history`, and `detail`. More information on the different levels can be found below. For all the info levels a specific set of sources can be specified from one to a list, to all (by omitting the `source` option). Specific sources are then available via the `sources` attribute of the returned object. {{ d['examples/example.py|idio|pycon|pyg']['get-event-level-cites'] }} Quantitative information is available for the requested sources divided into the same categories provided by summary level info (`views`, `shares`, `bookmarks`, `citations`). If a category is not populated, eg `shares` for the twitter source then it will return `None`. {{ d['examples/example.py|idio|pycon|pyg']['print-cites-metrics'] }} Further information about the source itself and the last time the ALM App instance updated its records are also available from attributes of the source object. {{ d['examples/example.py|idio|pycon|pyg']['source-cites-attributes'] }} Working with data ------------------- When requesting more detailed data there are two options `event` and `history`. The `history` option provides information on the ALM over a series of timepoints. These timepoints are those when the ALM App polled the data source rather than the date or time of specific events. Finally the `detail` level provides both event and history data. Event level data provides information on the specific events contributing to an ALM count. For instance, this will provide information on the individual tweets contributing to the overall count or individual citation events to the article of interest. ###Working with histories### History data is parsed from the original JSON to an ordered list of duples where the first element is a `datetime.datetime` object and the second is the integer total count for that metric. It is obtained from the `histories` attribute of the source object. The list is ordered from oldest to newest record. {{ d['examples/example.py|idio|pycon|pyg']['get-history-level-cites'] }} The number of elements in the `histories` list reflects the frequency with which the App instance updates the record and is not sensitive to the actual events which cause the count. ###Working with events### The event information is available via the `events` attribute on the source. Event data is not parsed direct from the return JSON object and needs to be handled by the user depending on their needs. {{ d['examples/example.py|idio|pycon|pyg']['get-event-level-cites'] }} {{ d['examples/example.py|idio|pycon|pyg']['print-cites-events'] }} The `events` module provides a set of classes for handling specific types of events.<file_sep>import unittest import pyalm.utilities.plossearch as search import datetime import pprint import json class SetUp(unittest.TestCase): def setUp(self): self.query = {'author' : 'Neylon'} self.start_date = datetime.datetime(2007, 1, 1) self.end_date = datetime.datetime(2013, 12, 31, 12, 34, 01) self.fields = ['title', 'doi'] self.test_query = search.Request(self.query, self.fields) class TestRequests(SetUp): def testBasicQuery(self): test_response = self.test_query.get() self.assertEqual(self.test_query.response.status_code, 200) self.assertGreater(len(test_response['response']['docs']), 6) def testQueryWithYearInts(self): self.test_query.search_date(2013, 2014) test_response = self.test_query.get() self.assertEqual(self.test_query.response.status_code, 200) self.assertEqual(len(test_response['response']['docs']), 3) def testQueryWithYearDatetimes(self): self.test_query.search_date(self.start_date, self.end_date) test_response = self.test_query.get() self.assertEqual(self.test_query.response.status_code, 200) self.assertEqual(len(test_response['response']['docs']), 7) def testQueryWithPaging(self): test_response = self.test_query.get() self.assertEqual(self.test_query.response.status_code, 200) self.assertGreater(len(test_response['response']['docs']), 6) class TestCollectDOIs(unittest.TestCase): def setUp(self): self.query = {'author' : 'Neylon'} self.start_date = datetime.datetime(2007, 1, 1) self.end_date = datetime.datetime(2013, 12, 31, 12, 34, 01) def testCollectDOIs(self): dois = search.collect_dois(self.query, (self.start_date, self.end_date)) self.assertIsInstance(dois, list) self.assertEqual(len(dois), 7) class TestFormattingFunctions(SetUp): def testSearchYear(self): self.test_query.search_year(2013) self.assertEqual(self.test_query.query['publication_date'], '[2013-01-01T00:00:00Z TO 2013-12-31T23:59:59Z]') if __name__ == "__main__": unittest.main() <file_sep># Higher level interface for interacting with specific classes of events import pyalm as alm import cleanup from utils import dictmapper, MappingRule as to ContributorBase = dictmapper('ContributorBase', { 'contributor_role' : ['contributor_role'], 'first_author': to(['first_author'], cleanup._text_to_bool), 'given_name': ['given_name'], 'sequence': ['sequence'], 'surname': ['surname'] } ) class Contributor(ContributorBase): def __repr__(self): return '<%s: %s%s>' % (type(self).__name__, self.given_name, self.surname) CrossrefBase = dictmapper('CrossrefBase', { 'article_title' : ['event','article_title'], 'doi' : ['event','doi'], 'fl_count' : to(['event','fl_count'], cleanup._parse_numbers_to_int), 'issn' : ['event','issn'], 'journal_abbreviation' : ['event','journal_abbreviation'], 'journal_title' : ['event','journal_title'], 'publication_type' : ['event','publication_type'], 'publication_year' : to(['event','year'], cleanup._parse_numbers_to_int), 'first_page' : to(['event', 'first_page'], cleanup._parse_numbers_to_int), 'issue' : to(['event', 'issue'], cleanup._parse_numbers_to_int), 'volume' : to(['event', 'volume'], cleanup._parse_numbers_to_int), 'contributors' : to(['event','contributors', 'contributor'], lambda l: map(Contributor, l) if l is not None else None) } ) class CrossRef(CrossrefBase): def __repr__(self): return '<%s %s:%s>' % (type(self).__name__, self.article_title, self.doi) TweetBase = dictmapper('TweetBase', { 'created_at' : to(['event', 'created_at'], cleanup._parse_dates_to_datetime), 'id' : ['event', 'id'], 'user' : ['event', 'user'], 'user_name' : ['event', 'user_name'], 'user_profile_image' : ['event', 'user_profile_image'], 'text' : ['event', 'text'], 'url' : ['event_url'], 'time' : ['event_time'], 'event_csl' : ['event_csl'] } ) class Tweet(TweetBase): def __repr__(self): return '<%s %s:%s>' % (type(self).__name__, self.user, self.text) WikiBase = dictmapper('WikiBase', { 'ca': ['ca'], 'commons': ['commons'], 'cs': ['cs'], 'de': ['de'], 'en': ['en'], 'es': ['es'], 'fi': ['fi'], 'fr': ['fr'], 'hu': ['hu'], 'it': ['it'], 'ja': ['ja'], 'ko': ['ko'], 'nl': ['nl'], 'no': ['no'], 'pl': ['pl'], 'pt': ['pt'], 'ru': ['ru'], 'sv': ['sv'], 'total': ['total'], 'uk': ['uk'], 'vi': ['vi'], 'zh': ['zh']}) class WikiRef(WikiBase): def __repr__(self): return '<%s Citations:%s>' % (type(self).__name__, self.total) # MendeleyBase = dictmapper('MendeleyBase', # { # 'readers' : ['events', 'readers'], # 'discipline' : ['events', 'discipline'], # 'country' : ['events', 'country'], # 'status' : ['events', 'status'], # 'events_csl' : ['events_csl'] # } # ) # class Mendeley(MendeleyBase): # def __repr__(self): # return '<%s Readers:%s>' % (type(self).__name__, self.readers) def mendeley_events(object): out = object.events out['url'] = object.events_url out['events_csl'] = object.events_csl out['events_url'] = object.events_url return out FacebookBase = dictmapper('FacebookBase', { 'url' : ['url'], 'share_count' : ['share_count'], 'like_count' : ['like_count'], 'comment_count' : ['comment_count'], 'click_count' : ['click_count'], 'total_count' : ['total_count'] } ) class Facebook(FacebookBase): def __repr__(self): return '<%s Total:%s>' % (type(self).__name__, self.total_count) NatureBase = dictmapper('NatureBase', { 'blog' : ['event', 'blog'], 'links_to_doi' : ['event', 'links_to_doi'], 'percent_complex_words' : ['event', 'percent_complex_words'], 'popularity' : ['event', 'popularity'], 'created_at' : ['event', 'created_at'], 'title' : ['event', 'title'], 'body' : ['event', 'body'], 'updated_at' : ['event', 'updated_at'], 'flesch' : ['event', 'flesch'], 'url' : ['event', 'url'], 'blog_id' : ['event', 'blog_id'], 'id' : ['event', 'id'], 'hashed_id' : ['event', 'hashed_id'], 'num_words' : ['event', 'num_words'], 'published_at' : ['event', 'published_at'], 'fog' : ['event', 'fog'], 'event_time' : ['event_time'], 'event_url' : ['event_url'], 'event_csl' : ['event_csl'] } ) class Nature(NatureBase): def __repr__(self): return '<%s: %s>' % (type(self).__name__, self.title) PubmedBase = dictmapper('PubmedBase', { 'event' : ['event'], 'event_url' : ['event_url'] } ) class Pubmed(PubmedBase): def __repr__(self): return '<%s: %s>' % (type(self).__name__, self.event) ScopusBase = dictmapper('ScopusBase', { 'fa' : [ '@_fa' ], 'link' : [ 'link' ], 'prism_url' : [ 'prism:url' ], 'dc_identifier' : [ 'dc:identifier' ], 'eid' : [ 'eid' ], 'dc_title' : [ 'dc:title' ], 'dc_creator' : [ 'dc:creator' ], 'prism_publicationName' : [ 'prism:publicationName' ], 'prism_issn' : [ 'prism:issn' ], 'prism_eIssn' : [ 'prism:eIssn' ], 'prism_volume' : [ 'prism:volume' ], 'prism_issueIdentifier' : [ 'prism:issueIdentifier' ], 'prism_coverDate' : [ 'prism:coverDate' ], 'prism_coverDisplayDate' : [ 'prism:coverDisplayDate' ], 'prism_doi' : [ 'prism:doi' ], 'citedby_count' : [ 'citedby-count' ], 'affiliation' : [ 'affiliation' ], 'pubmed_id' : [ 'pubmed-id' ], 'prism_aggregationType' : [ 'prism:aggregationType' ], 'subtype' : [ 'subtype' ], 'subtypeDescription' : [ 'subtypeDescription' ] } ) class Scopus(ScopusBase): def __repr__(self): return '<%s: %s>' % (type(self).__name__, self.citedby_count) CounterBase = dictmapper('CounterBase', { 'month' : [ 'month' ], 'year' : [ 'year' ], 'pdf_views' : [ 'pdf_views' ], 'xml_views' : [ 'xml_views' ], 'html_views' : [ 'html_views' ] } ) class Counter(CounterBase): def __repr__(self): return '<%s PDF:%s XML:%s HTML:%s>' % (type(self).__name__, self.pdf_views, self.xml_views, self.html_views) ResearchBloggingBase = dictmapper('ResearchBloggingBase', { 'post_title' : [ 'event', 'post_title' ], 'blog_name' : [ 'event', 'blog_name' ], 'blogger_name' : [ 'event', 'blogger_name' ], 'received_date' : [ 'event', 'received_date' ], 'published_date' : [ 'event', 'published_date' ], 'post_URL' : [ 'event', 'post_URL' ], 'citations' : to(['event','citations'], cleanup._parse_citations), 'id' : [ 'event', 'id' ], 'event_url' : [ 'event_url' ] } ) class ResearchBlogging(ResearchBloggingBase): def __repr__(self): return '<%s: %s>' % (type(self).__name__, self.post_title) PMCBase = dictmapper('PMCBase', { 'month' : [ 'month' ], 'year' : [ 'year' ], 'pdf' : [ 'pdf' ], 'unique_ip' : [ 'unique-ip' ], 'full_text' : [ 'full-text' ], 'abstract' : [ 'abstract' ], 'scanned_summary' : [ 'scanned-summary' ], 'scanned_page_browse' : [ 'scanned-page-browse' ], 'figure' : [ 'figure' ], 'supp_data' : [ 'supp-data' ], 'cited_by' : [ 'cited-by' ] } ) class PMC(PMCBase): def __repr__(self): return '<%s YR/MO:%s/%s PDF:%s>' % (type(self).__name__, self.year, self.month, self.pdf) FigshareBase = dictmapper('FigshareBase', { 'files' : [ 'month' ], 'pos_in_sequence' : [ 'pos_in_sequence' ], 'stats' : [ 'stats' ], 'users' : [ 'users' ], 'links' : [ 'links' ], 'tags' : [ 'tags' ], 'title' : [ 'figshare_url' ], 'figshare_url': [ 'figshare_url' ], 'defined_type' : [ 'defined_type' ], 'doi' : [ 'doi' ], 'published_date' : to(['published_date'], cleanup._parse_dates_figshare), 'article_id' : [ 'article_id' ], 'categories' : [ 'categories' ], 'description' : [ 'description' ] } ) class Figshare(FigshareBase): def __repr__(self): return '<%s Downloads:%s Pageviews:%s Likes:%s>' % (type(self).__name__, self.stats['downloads'], self.stats['page_views'], self.stats['likes']) PlosCommentsBase = dictmapper('PlosCommentsBase', { 'originalTitle': [ 'event', 'originalTitle' ], 'title': [ 'event', 'title' ], 'body': [ 'event', 'body' ], 'originalBody': [ 'event', 'originalBody' ], 'truncatedBody': [ 'event', 'truncatedBody' ], 'bodyWithUrlLinkingNoPTags': [ 'event', 'bodyWithUrlLinkingNoPTags' ], 'truncatedBodyWithUrlLinkingNoPTags': [ 'event', 'truncatedBodyWithUrlLinkingNoPTags' ], 'bodyWithHighlightedText': [ 'event', 'bodyWithHighlightedText' ], 'competingInterestStatement': [ 'event', 'competingInterestStatement' ], 'truncatedCompetingInterestStatement': [ 'event', 'truncatedCompetingInterestStatement' ], 'annotationUri': [ 'event', 'annotationUri' ], 'creatorID': [ 'event', 'creatorID' ], 'creatorDisplayName': [ 'event', 'creatorDisplayName' ], 'creatorFormattedName': [ 'event', 'creatorFormattedName' ], 'articleID': [ 'event', 'articleID' ], 'articleDoi': [ 'event', 'articleDoi' ], 'articleTitle': [ 'event', 'articleTitle' ], 'created' : to(['event', 'created'], cleanup._parse_dates_to_datetime), 'createdFormatted' : to(['event', 'createdFormatted'], cleanup._parse_dates_to_datetime), 'type': [ 'event', 'type' ], 'replies': [ 'event', 'replies' ], 'lastReplyDate' : to(['event', 'lastReplyDate'], cleanup._parse_dates_to_datetime), 'totalNumReplies': [ 'event' ,'totalNumReplies' ], 'event_time' : to(['event_time'], cleanup._parse_dates_to_datetime), 'event_url' : [ 'event_url' ], 'event_csl' : [ 'event_csl' ] } ) class PlosComments(PlosCommentsBase): def __repr__(self): return '<%s: %s>' % (type(self).__name__, self.title) ScienceseekerBase = dictmapper('ScienceseekerBase', { 'title': [ 'event', 'title' ], 'id': [ 'event', 'id' ], 'link': [ 'event', 'link' ], 'updated' : to(['event', 'updated'], cleanup._parse_dates_to_datetime), 'author': [ 'event', 'author' ], 'summary': [ 'event', 'summary' ], 'citations': [ 'event', 'citations' ], 'community': [ 'event', 'community' ], 'category': [ 'event', 'category' ], 'source': [ 'event', 'source' ], 'lang': [ 'event', 'lang' ], 'event_time' : to(['event_time'], cleanup._parse_dates_to_datetime), 'event_url': [ 'event_url' ], 'event_csl': [ 'event_csl' ] } ) class Scienceseeker(ScienceseekerBase): def __repr__(self): return '<%s: %s>' % (type(self).__name__, self.title) F1000Base = dictmapper('F1000Base', { 'classifications': [ 'event', 'classifications' ], 'doi': [ 'event', 'doi' ], 'f1000_id': [ 'event', 'f1000_id' ], 'updated_at' : to(['event', 'updated_at'], cleanup._parse_dates_to_datetime), 'year': [ 'event', 'year' ], 'month': [ 'event', 'month' ], 'score': [ 'event', 'score' ], 'url': [ 'event', 'url' ], 'event_url': [ 'event_url' ] } ) class F1000(F1000Base): def __repr__(self): return '<%s: %s>' % (type(self).__name__, self.doi) WordpressBase = dictmapper('WordpressBase', { 'title': [ 'event', 'title' ], 'author': [ 'event', 'author' ], 'link': [ 'event', 'link' ], 'epoch_time': [ 'event', 'epoch_time' ], 'guid': [ 'event', 'guid' ], 'content': [ 'event', 'content' ], 'event_time' : to(['event_time'], cleanup._parse_dates_to_datetime), 'event_url': [ 'event_url' ], 'event_csl': [ 'event_csl' ] } ) class Wordpress(WordpressBase): def __repr__(self): return '<%s %s:%s>' % (type(self).__name__, self.author, self.title) RedditBase = dictmapper('RedditBase', { 'domain': [ 'event', 'domain' ], 'banned_by': [ 'event', 'banned_by' ], 'media_embed': [ 'event', 'media_embed' ], 'subreddit': [ 'event', 'subreddit' ], 'selftext_html': [ 'event', 'selftext_html' ], 'selftext': [ 'event', 'selftext' ], 'likes': [ 'event', 'likes' ], 'user_reports': [ 'event', 'user_reports' ], 'secure_media': [ 'event', 'secure_media' ], 'link_flair_text': [ 'event', 'link_flair_text' ], 'id': [ 'event', 'id' ], 'gilded': [ 'event', 'gilded' ], 'secure_media_embed': [ 'event', 'secure_media_embed' ], 'clicked': [ 'event', 'clicked' ], 'report_reasons': [ 'event', 'report_reasons' ], 'author': [ 'event', 'author' ], 'media': [ 'event', 'media' ], 'score': [ 'event', 'score' ], 'approved_by': [ 'event', 'approved_by' ], 'over_18': [ 'event', 'over_18' ], 'hidden': [ 'event', 'hidden' ], 'num_comments': [ 'event', 'num_comments' ], 'thumbnail': [ 'event', 'thumbnail' ], 'subreddit_id': [ 'event', 'subreddit_id' ], 'edited': to([ 'event', 'edited' ], cleanup._parse_unix), 'link_flair_css_class': [ 'event', 'link_flair_css_class' ], 'author_flair_css_class': [ 'event', 'author_flair_css_class' ], 'downs': [ 'event', 'downs' ], 'saved': [ 'event', 'saved' ], 'stickied': [ 'event', 'stickied' ], 'is_self': [ 'event', 'is_self' ], 'permalink': [ 'event', 'permalink' ], 'name': [ 'event', 'name' ], 'created': to([ 'event', 'created' ], cleanup._parse_unix), 'url': [ 'event', 'url' ], 'author_flair_text': [ 'event', 'author_flair_text' ], 'title': [ 'event', 'title' ], 'created_utc': to([ 'event', 'created_utc' ], cleanup._parse_unix), 'distinguished': [ 'event', 'distinguished' ], 'mod_reports': [ 'event', 'mod_reports' ], 'visited': [ 'event', 'visited' ], 'num_reports': [ 'event', 'num_reports' ], 'ups': [ 'event', 'ups' ], 'event_time' : to(['event_time'], cleanup._parse_dates_to_datetime), 'event_url': [ 'event_url' ], 'event_csl': [ 'event_csl' ] } ) class Reddit(RedditBase): def __repr__(self): return '<%s %s:%s>' % (type(self).__name__, self.author, self.title) DataciteBase = dictmapper('DataciteBase', { 'relatedIdentifier': [ 'event', 'relatedIdentifier' ], 'doi': [ 'event', 'doi' ], 'publicationYear': [ 'event', 'publicationYear' ], 'publisher': [ 'event', 'publisher' ], 'title': [ 'event', 'title' ], 'creator': [ 'event', 'creator' ], 'event_url': [ 'event_url' ] } ) class Datacite(DataciteBase): def __repr__(self): return '<%s: %s>' % (type(self).__name__, self.doi) ArticlecoverageBase = dictmapper('ArticlecoverageBase', { 'link_state': [ 'event', 'link_state' ], 'publication': [ 'event', 'publication' ], 'published_on' : to(['event', 'published_on'], cleanup._parse_dates_to_datetime), 'referral': [ 'event', 'referral' ], 'title': [ 'event', 'title' ], 'type': [ 'event', 'type' ], 'language': [ 'event', 'language' ], 'event_url': [ 'event_url' ], 'event_time' : to(['event_time'], cleanup._parse_dates_to_datetime) } ) class Articlecoverage(ArticlecoverageBase): def __repr__(self): return '<%s: %s>' % (type(self).__name__, self.title) class ArticlecoverageCurated(ArticlecoverageBase): def __repr__(self): return '<%s: %s>' % (type(self).__name__, self.title) <file_sep># To get a PLOS API Key register for an account by following the instructions at # http://api.plos.org/registration/ # For other instances you will need to contact the manager of that instance. API_KEY = { 'plos' : 'YOUR API KEY GOES HERE', 'ojs' : 'YOUR API KEY GOES HERE', 'copernicus' : 'YOUR API KEY GOES HERE'}<file_sep>pyalm ===== A Python Wrapper for the PLOS Article Level Metrics App API ----------------------------------------------------------- The wrapper is based on the orcid-python wrapper by github users scholrly which can be found at https://github.com/scholrly/orcid-python. Installation ------------ Clone the github repository to your local machine as desired and then run python setup.py install or python setup.py develop if you wish to work on the code. To use the API you will need an api key. Look for the api_key.example.py file for instructions on how to get an API key for the PLOS installation and where to put it. Testing and Contributions ------------------------- [![Build Status](https://travis-ci.org/cameronneylon/pyalm.png?branch=master)](https://travis-ci.org/cameronneylon/pyalm) [![Coverage Status](https://img.shields.io/coveralls/cameronneylon/pyalm.svg)](https://coveralls.io/r/cameronneylon/pyalm?branch=master) pyalm is currently tested via a small unittest suite and continuous integration via Travis-CI with tests run for Python 2.7. Feel free to fork and to issue a pull request for any contributions and improvements (including getting it to pass tests under other Python versions). <file_sep># try: # from api_key import * # except ImportError: # This will happen when external integration platforms try to get key # API_KEY = {} # API_KEY['plos'] = 'FAKE-TEST-KEY' # APIS = { 'plos' : { # 'url': "http://alm.plos.org/api/v5/articles", # 'key': API_KEY.get('plos') # }, # 'ojs' : { # 'url': None, # 'key': API_KEY.get('ojs') # }, # 'copernicus' : { # 'url': None, # 'key': API_KEY.get('copernicus') # }} API_KEY = None PYALM_LOCATION = "~/.pyalm" """ This is the location of the api keys and url stored on the filesystem. Currently, it uses a file directly under a tilde, so that windows users don't have to feel as much pain when using the API. Usually this is something like ``~/.pyalm`` """ PLOS_KEY_ENVVAR = "PLOS_API_KEY" ELIFE_KEY_ENVVAR = "ELIFE_API_KEY" CROSSREF_KEY_ENVVAR = "CROSSREF_API_KEY" PKP_KEY_ENVVAR = "PKP_API_KEY" COPERNICUS_KEY_ENVVAR = "COPERNICUS_API_KEY" PENSOFT_KEY_ENVVAR = "PENSOFT_API_KEY" """ These are the names of the ``os.environ`` keys to look for. """ PLOS_URL_ENVVAR = "PLOS_URL" ELIFE_URL_ENVVAR = "ELIFE_URL" CROSSREF_URL_ENVVAR = "CROSSREF_URL" PKP_URL_ENVVAR = "PKP_URL" COPERNICUS_URL_ENVVAR = "COPERNICUS_URL" PENSOFT_URL_ENVVAR = "PENSOFT_URL" """ These are the names of the ``os.environ`` urls to look for. """ <file_sep>import email.utils import datetime import requests def _text_to_bool(response): if (type(response) == str) or (type(response) == unicode): return response == 'true' else: return response def _parse_dates_to_datetime(response): return _time_parse_helper(response, '%Y-%m-%dT%H:%M:%SZ') def _parse_dates_figshare(response): return _time_parse_helper(response, '%Y-%m-%d %H:%M:%S') def _time_parse_helper(response, format): if (type(response) == str) or (type(response) == unicode): try: return datetime.datetime.strptime(response, format) except ValueError: tup = email.utils.parsedate_tz(response)[0:6] return datetime.datetime(*tup) else: return response def _parse_unix(unix): return datetime.datetime.utcfromtimestamp(unix) def _parse_issued(issued): return datetime.datetime.strptime('-'.join([str(x) for x in issued['date-parts'][0]]), '%Y-%m-%d') def _parse_numbers_to_int(response): if (type(response) == str) or (type(response) == unicode): return int(response) else: return response def _process_histories(history): timepoints= [] for timepoint in history: timepoints.append([_parse_dates_to_datetime(timepoint.get('update_date')), _parse_numbers_to_int(timepoint.get('total'))]) timepoints.sort(key=lambda l: l[0]) return timepoints def _parse_day(datedict): for d in datedict: date = '-'.join([ str(d['year']), str(d['month']), str(d['day']) ]) d['date'] = datetime.datetime.strptime(date, '%Y-%m-%d') return datedict def _parse_month(datedict): for d in datedict: date='-'.join([ str(d['year']), str(d['month']) ]) d['date'] = datetime.datetime.strptime(date, '%Y-%m') return datedict def _parse_year(datedict): for d in datedict: d['date'] = datetime.datetime.strptime(str(d['year']), '%Y') return datedict def _parse_citations(citations): citations_ = [] for d in citations['citation']: d['full_citation'] = _crossref_cn(d['doi']) citations_.append(d) return citations_ def _crossref_cn(doi): ''' _crossref_cn("10.1126/science.1157784") ''' res = requests.get("http://dx.doi.org/" + doi, headers={'Accept' : 'text/x-bibliography; style=apa; locale=en-US'}, allow_redirects=True) if res.status_code == 200: return res.text else: return None <file_sep># This file used directly from the orcid-python library by <NAME> # # Used under the terms of the MIT license as per: # https://github.com/scholrly/orcid-python/blob/master/LICENSE-MIT.txt # # Original version available at: # https://github.com/scholrly/orcid-python/blob/bd4b7b350098c625bc05cbb260435a42a951bff2/orcid/utils.py def dict_value_from_path(d, path): cur_dict = d for key in path[:-1]: cur_dict = cur_dict.get(key, {}) return cur_dict.get(path[-1], None) if cur_dict is not None else None def dictmapper(typename, mapping): """ A factory to create `namedtuple`-like classes from a field-to-dict-path mapping:: Person = dictmapper({'person':('person','name')}) example_dict = {'person':{'name':'John'}} john = Person(example_dict) assert john.name == 'John' If a function is specified as a mapping value instead of a dict "path", it will be run with the backing dict as its first argument. """ def init(self, d, *args, **kwargs): """ Initialize `dictmapper` classes with a dict to back getters. """ self._original_dict = d def getter_from_dict_path(path): if not callable(path) and len(path) < 1: raise ValueError('Dict paths should be iterables with at least one' ' key or callable objects that take one argument.') def getter(self): cur_dict = self._original_dict if callable(path): return path(cur_dict) return dict_value_from_path(cur_dict, path) return getter prop_mapping = dict((k, property(getter_from_dict_path(v))) for k, v in mapping.iteritems()) prop_mapping['__init__'] = init return type(typename, tuple(), prop_mapping) class MappingRule(object): def __init__(self, path, further_func = lambda x : x): self.path = path self.further_func = further_func def __call__(self, d): return self.further_func(dict_value_from_path(d, self.path)) <file_sep>import requests from utils import dictmapper, MappingRule as to import cleanup import config BASE_HEADERS = {'Accept': 'application/json'} MetricsBase = dictmapper('MetricsBase', {'citations': to(['citations'], cleanup._parse_numbers_to_int), 'comments': to(['comments'], cleanup._parse_numbers_to_int), 'html': to(['html'], cleanup._parse_numbers_to_int), 'likes': to(['likes'], cleanup._parse_numbers_to_int), 'pdf': to(['pdf'], cleanup._parse_numbers_to_int), 'readers': to(['readers'], cleanup._parse_numbers_to_int), 'shares': to(['shares'], cleanup._parse_numbers_to_int), 'total': to(['total'], cleanup._parse_numbers_to_int) } ) class Metrics(MetricsBase): def __repr__(self): return """ <%s total:%s readers:%s pdf:%s html:%s comments:%s likes:%s> """ % (type(self).__name__, self.total, self.readers, self.pdf, self.html, self.comments, self.likes) SourceBase = dictmapper('SourceBase', { 'name': ['name'], 'display_name': ['display_name'], 'group_name': ['group_name'], 'events_url': ['events_url'], 'update_date': to(['update_date'], cleanup._parse_dates_to_datetime), 'events': ['events'], 'events_csl': ['events_csl'], 'metrics': to(['metrics'], lambda l: Metrics(l) if l is not None else None), 'by_day': to(['by_day'], cleanup._parse_day), 'by_month': to(['by_month'], cleanup._parse_month), 'by_year': to(['by_year'], cleanup._parse_year) } ) class Source(SourceBase): def __repr__(self): return "<%s %s:%s>" % (type(self).__name__, self.display_name, self.metrics.total) ArticleALMBase = dictmapper('ArticleALMBase', { 'doi': ['doi'], 'mendeley_uuid': ['mendeley_uuid'], 'pmcid': ['pmcid'], 'pmid': ['pmid'], 'issued': to(['issued'], cleanup._parse_issued), 'update_date': to(['update_date'], cleanup._parse_dates_to_datetime), 'url': ['canonical_url'], 'title': ['title'], 'cited': to(['cited'], cleanup._parse_numbers_to_int), 'saved': to(['saved'], cleanup._parse_numbers_to_int), 'discussed': to(['discussed'], cleanup._parse_numbers_to_int), 'viewed': to(['viewed'], cleanup._parse_numbers_to_int) } ) class ArticleALM(ArticleALMBase): _sources = {} _resp_json = None def _load_sources(self): for src in self._resp_json.get('sources', None): self._sources[src['name']] = Source(src) @property def sources(self): if self._sources == {}: self._load_sources() return self._sources def __repr__(self): return "<%s %s, DOI %s>" % (type(self).__name__, self.title, self.doi) def get_alm(identifiers=None, id_type=None, info=None, source=None, publisher=None, order=None, per_page=None, page=None, instance='plos', **kwargs): """ Get summary level alms based on an identifier or identifiers :param ids: One or more DOIs, PMCIDs, etc. :param api_key: An API key, looks for api key first, or pass one in. :param id_type: One of doi, pmid, pmcid, or mendeley_uuid :param info: One of summary or detail :param source: One source. To get many sources, make many calls. :param publisher: Filter articles to a given publisher, using a crossref_id. :para order: Results are sorted by descending event count when given the source name, e.g. &order=wikipedia. Otherwise (the default) results are sorted by date descending. When using &source=x, we can only sort by data or that source, not a different source. :param per_page: Number of results to return, use in combination with page. :param page: Page to return, use in combination with per_page. :param instance: One of plos, elife, crossref, pkp, pensoft, or copernicus. :param **kwargs: Additional named arguments passed on to requests.get Usage: >>> import pyalm >>> >>> # Get a single article >>> article = pyalm.get_alm("10.1371/journal.pone.0029797", info="summary") >>> article['meta'] >>> article['meta']['total'] >>> article['articles'] >>> article['articles'][0].title >>> >>> # Get summary or detailed data >>> ## summary >>> pyalm.get_alm("10.1371/journal.pone.0029797", info="summary")['articles'][0]._resp_json >>> ## detail >>> pyalm.get_alm("10.1371/journal.pone.0029797", info="detail")['articles'][0]._resp_json >>> >>> # Multiple articles >>> ids = ["10.1371/journal.pone.0029797","10.1371/journal.pone.0029798"] >>> articles = pyalm.get_alm(ids, info="summary") >>> len(articles['articles']) >>> for article in articles['articles']: >>> print article.title,"DOI:", article.doi, >>> print "Views:", article.viewed >>> >>> # Search by source >>> articles = pyalm.get_alm(source="mendeley", info="summary") >>> >>> # Search by publisher >>> ## first, get some publisher ids via the CrossRef API >>> import requests >>> ids = requests.get("http://api.crossref.org/members") >>> id = [x['id'] for x in ids.json()['message']['items']][0] >>> pyalm.get_alm(publisher=id, info="summary") >>> >>> # Order results >>> ## order by a source, orders by descending event count in that source >>> articles = pyalm.get_alm(order="mendeley", per_page=10) >>> [x.sources['mendeley'].metrics.total for x in articles['articles']] >>> >>> ## not specifying an order, results sorted by date descending >>> articles = pyalm.get_alm(info="summary") >>> [ x.update_date for x in articles['articles'] ] >>> >>> # Paging >>> pyalm.get_alm(source="mendeley", info="summary", per_page=1) >>> pyalm.get_alm(source="mendeley", info="summary", per_page=2) >>> pyalm.get_alm(source="mendeley", info="summary", per_page=2, page=10) >>> >>> # Search against other Lagotto instances >>> pyalm.get_alm(instance="crossref", per_page=5) >>> pyalm.get_alm(instance="pkp", per_page=5) >>> pyalm.get_alm(instance="elife", per_page=5) >>> >>> # You can pass on additional options to requests.get >>> pyalm.get_alm("10.1371/journal.pone.0029797", info="summary", timeout=0.001) >>> >>> # Parse events data >>> from pyalm import events >>> article = pyalm.get_alm("10.1371/journal.pone.0029797", info="detail") >>> >>> ## twitter >>> [events.Tweet(x) for x in article['articles'][0].sources['twitter'].events] >>> ## wikipedia >>> dat = events.WikiRef(article['articles'][0].sources['wikipedia'].events) >>> dat.en >>> dat.fr >>> ## Mendeley >>> events.mendeley_events(article['articles'][0].sources['mendeley']) >>> ## Facebook >>> out = events.Facebook(article['articles'][0].sources['facebook'].events[0]) >>> out.click_count >>> articles = pyalm.get_alm(info="detail", source="facebook", per_page=10) >>> [events.Facebook(x.sources['facebook'].events[0]) for x in articles['articles']] >>> ## CrossRef >>> [events.CrossRef(x) for x in article['articles'][0].sources['crossref'].events] >>> ## Nature >>> [events.Nature(x) for x in article['articles'][0].sources['nature'].events] >>> ## Pubmed >>> out = [events.Pubmed(x) for x in article['articles'][0].sources['pubmed'].events] >>> out[0].event >>> out[0].event_url >>> ## Counter (PLOS views data) >>> events.Counter(article['articles'][0].sources['counter'].events[0]) >>> [events.Counter(x) for x in article['articles'][0].sources['counter'].events] >>> ## Research Blogging >>> out = events.ResearchBlogging(article['articles'][0].sources['researchblogging'].events[0]) >>> out.blog_name >>> out.citations >>> [ x['full_citation'] for x in out.citations ] >>> [events.ResearchBlogging(x) for x in article['articles'][0].sources['researchblogging'].events] >>> ## PMC >>> out = events.PMC(article['articles'][0].sources['pmc'].events[0]) >>> out.pdf >>> out.full_text >>> [events.PMC(x) for x in article['articles'][0].sources['pmc'].events] >>> ## Figshare >>> out = events.Figshare(article['articles'][0].sources['figshare'].events[0]) >>> out.doi >>> out.files >>> [events.Figshare(x) for x in article['articles'][0].sources['figshare'].events] >>> ## PLOS journal comments >>> out = events.PlosComments(article['articles'][0].sources['plos_comments'].events[0]) >>> out.title >>> out.event_time.isoformat() >>> [events.PlosComments(x) for x in article['articles'][0].sources['plos_comments'].events] >>> ## Sciencseeker >>> articles = pyalm.get_alm(info="detail", source="scienceseeker", order="scienceseeker") >>> out = events.Scienceseeker(articles[0].sources['scienceseeker'].events[0]) >>> out.title >>> out.event_time.isoformat() >>> [events.Scienceseeker(x.sources['scienceseeker'].events[0]) for x in articles] >>> ## f1000 >>> article = pyalm.get_alm("10.1371/journal.pbio.1001041", info="detail") >>> out = events.F1000(article['articles'][0].sources['f1000'].events[0]) >>> out.updated_at >>> [events.F1000(x) for x in article['articles'][0].sources['f1000'].events] >>> ## Wordpress >>> article = pyalm.get_alm("10.1371/journal.pcbi.1000361", info="detail") >>> out = events.Wordpress(article['articles'][0].sources['wordpress'].events[0]) >>> out.title >>> out.event_time.isoformat() >>> [events.Wordpress(x) for x in article['articles'][0].sources['wordpress'].events] >>> ## Reddit >>> article = pyalm.get_alm("10.1371/journal.pone.0111081", info="detail") >>> out = events.Reddit(article['articles'][0].sources['reddit'].events[0]) >>> out.title >>> out.event_time.isoformat() >>> [events.Reddit(x) for x in article['articles'][0].sources['reddit'].events] >>> ## Datacite >>> article = pyalm.get_alm("10.1371/journal.pone.0081508", info="detail") >>> out = events.Datacite(article['articles'][0].sources['datacite'].events[0]) >>> out.creator >>> out.title >>> [events.Datacite(x) for x in article['articles'][0].sources['datacite'].events] >>> ## Articlecoverage and Articlecoveragecurated >>> article = pyalm.get_alm("10.1371/journal.pmed.0020124", info="detail") >>> events.Articlecoverage(article['articles'][0].sources['articlecoverage'].events[0]) >>> events.ArticlecoverageCurated(article['articles'][0].sources['articlecoveragecurated'].events[0]) >>> [events.Articlecoverage(x) for x in article['articles'][0].sources['articlecoverage'].events] """ if type(identifiers) != str and identifiers != None: identifiers = ','.join(identifiers) # _test_length(source) # _test_int('page', page) # _test_int('per_page', per_page) _test_values('info', info, ['summary','detail']) # _test_values('id_type', id_type, ['doi','pmid','pmcid','mendeley_uuid']) _test_values('instance', instance, ['plos','crossref','copernicus','elife','pensoft','pkp']) parameters = {'ids': identifiers, 'type': id_type, 'info': info, 'source': source, 'publisher': publisher, 'order': order, 'per_page': per_page, 'page': page, 'api_key': config.APIS.get(instance).get('key'), } url = config.APIS.get(instance).get('url') if url: resp = requests.get(url, params=parameters, headers=BASE_HEADERS, **kwargs) resp.raise_for_status() meta = _get_meta(resp.json(), 'data') articles = [] for article_json in resp.json()['data']: articles.append(_process_json_to_article(article_json)) return { "meta": meta, "articles": articles } else: raise def _process_json_to_article(article_json): article = ArticleALM(article_json) article._sources = {} article._resp_json = article_json return article def _get_meta(res, key): res.pop(key, None) return res def _test_length(input): if type(input) != None and len(input) > 1: raise TypeError('Parameter "source" must be either None or length 1') def _test_int(name, input): if type(input) != None and type(input) != int: raise TypeError('Parameter "%s" must be type int' % name) def _test_values(name, input, values): if input.__class__ == str: input = input.split(' ') if type(input) != None: if len(input) > 1: raise TypeError('Parameter "%s" must be length 1' % name) if input[0] not in values: raise TypeError('Parameter "%s" must be one of %s' % (name, values)) def get_locals(input, values): return locals().values() <file_sep>import unittest import pyalm.pyalm as pyalm import datetime import pprint import json class TestOnline(unittest.TestCase): def setUp(self): self.test_doi = "10.1371/journal.pone.0029797" self.test_two_dois = ["10.1371/journal.pone.0029797","10.1371/journal.pone.0029798"] self.test_response_doi = "10.1371/journal.pone.0029797" self.test_response_doi2 = "10.1371/journal.pone.0029798" self.test_response_title = "Ecological Guild Evolution and the Discovery of the World's Smallest Vertebrate" self.test_response_title2 = "Mitochondrial Electron Transport Is the Cellular Target of the Oncology Drug Elesclomol" self.test_response_views = 32755 self.test_response_views2 = 3862 self.test_response_publication_date = datetime.datetime(2012, 1, 11, 8, 0, 0) self.test_response_mendeley_event_url = u'http://www.mendeley.com/research/ecological-guild-evolution-discovery-worlds-smallest-vertebrate/' self.test_source = 'twitter,counter,crossref,wikipedia,mendeley' def tearDown(self): del self.resp class TestRetrieveALMs(TestOnline): def testGet(self): self.resp = pyalm.get_alm(self.test_doi, source = self.test_source, info ='detail')[0] #Basic Tests self.assertEqual(self.resp.title, self.test_response_title) self.assertEqual(self.resp.doi, self.test_response_doi) self.assertGreaterEqual(self.resp.views, self.test_response_views) self.assertEqual(type(self.resp.update_date), datetime.datetime) self.assertEqual(self.resp.publication_date, self.test_response_publication_date) #Sources numeric tests self.assertGreaterEqual(self.resp.sources['twitter'].metrics.total, 9) self.assertGreaterEqual(self.resp.sources['counter'].metrics.total, 28887) self.assertGreaterEqual(self.resp.sources['crossref'].metrics.total, 7) #self.assertGreaterEqual(self.resp.sources['pmc'].metrics.total, 391) #Sources names and urls self.assertEqual(self.resp.sources['mendeley'].events_url, self.test_response_mendeley_event_url) #Sources metrics test self.assertGreaterEqual(self.resp.sources['twitter'].metrics.comments, 9) #Sources histories tests timepoints = self.resp.sources['crossref'].histories self.assertIsInstance(timepoints[0][0], datetime.datetime ) def testGetMultipleDOIs(self): self.resp = pyalm.get_alm(self.test_two_dois, info='summary') titles = [self.resp[0].title, self.resp[1].title] dois = [self.resp[0].doi, self.resp[1].doi] self.assertIn(self.test_response_title, titles) self.assertIn(self.test_response_title2, titles) self.assertIn(self.test_response_doi, dois) self.assertIn(self.test_response_doi2, dois) views = [self.resp[0].views, self.resp[1].views] views.sort() self.assertGreaterEqual(views[0], self.test_response_views2) self.assertGreaterEqual(views[1], self.test_response_views) class TestOffline(unittest.TestCase): def setUp(self): self.test_doi = "10.1371/journal.pone.0029797" self.test_response_doi = "10.1371/journal.pone.0029797" self.test_response_title = "TEST-JSON: Ecological Guild Evolution and the Discovery of the World's Smallest Vertebrate" self.test_response_views = 29278 self.test_response_publication_date = datetime.datetime(2012, 1, 11, 8, 0, 0) self.test_response_mendeley_event_url = u'http://www.mendeley.com/research/ecological-guild-evolution-discovery-worlds-smallest-vertebrate/' self.test_source = 'twitter' with open('test/test_data_history.json', 'r') as f: self.json_body = json.load(f)[0] self.mock_resp = pyalm.ArticleALM(self.json_body) self.mock_resp._resp_json = self.json_body def tearDown(self): del self.mock_resp del self.json_body class TestBasicElements(TestOffline): def testBasicElements(self): self.assertEqual(self.mock_resp.title, self.test_response_title) self.assertEqual(self.mock_resp.doi, self.test_response_doi) self.assertGreaterEqual(self.mock_resp.views, self.test_response_views) self.assertEqual(type(self.mock_resp.update_date), datetime.datetime) self.assertEqual(self.mock_resp.publication_date, self.test_response_publication_date) class TestSourcesNumbers(TestOffline): def testSourcesNumbers(self): self.assertEqual(self.mock_resp.sources['twitter'].metrics.total, 9) self.assertEqual(self.mock_resp.sources['counter'].metrics.total, 28887) self.assertEqual(self.mock_resp.sources['crossref'].metrics.total, 7) self.assertEqual(self.mock_resp.sources['pmc'].metrics.total, 391) self.assertEqual(self.mock_resp.sources['twitter'].metrics.total, 9) class TestSourcesAttributes(TestOffline): def testSourcesAttributes(self): self.assertEqual(self.mock_resp.sources['mendeley'].events_url, self.test_response_mendeley_event_url) self.assertEqual(self.mock_resp.sources['mendeley'].update_date, datetime.datetime(2013, 9, 15, 19, 42, 17)) class TestSourcesMetrics(TestOffline): def testSourcesMetrics(self): self.assertEqual(self.mock_resp.sources['twitter'].metrics.comments, 9) class TestSourcesHistories(TestOffline): def testWikipediaHistory(self): timepoints = self.mock_resp.sources['wikipedia'].histories self.assertEqual(timepoints[0][0], datetime.datetime(2012, 9, 19, 12, 56, 23)) self.assertEqual(timepoints[0][1], 206) self.assertEqual(len(timepoints), 10) def testMendeleyHistory(self): timepoints = self.mock_resp.sources['mendeley'].histories self.assertEqual(timepoints[0][0], datetime.datetime(2012, 1, 12, 8, 7, 32)) self.assertEqual(timepoints[0][1], 0) self.assertEqual(timepoints[83][0], datetime.datetime(2013, 9, 15, 19, 42, 18)) self.assertEqual(timepoints[83][1], 50) self.assertEqual(len(timepoints), 84) def testTwitterHistory(self): timepoints = self.mock_resp.sources['twitter'].histories if __name__ == "__main__": unittest.main() <file_sep># pyalm ''' pyalm library ~~~~~~~~~~~~~~~~~~~~~ pyalm is a Python client for the PLOS ALM API. Example usage: >>> import pyalm >>> pyalm.get_alm("10.1371/journal.pone.0029797", info="summary") <ArticleALM Ecological Guild Evolution and the Discovery of the World's Smallest Vertebrate, DOI 10.1371/journal.pone.0029797> ''' from .cleanup import * from .config import * from .events import * from .pyalm import get_alm from .utils import * import os import re def _insert_items(keydict, mdict, i): for p in keydict.iterkeys(): if bool(re.search(i, p, re.IGNORECASE)): if bool(re.search('URL', p)): mdict[i]['url'] = keydict[p] if bool(re.search('KEY', p)): mdict[i]['key'] = keydict[p] return mdict def _get_env_vars(): kk = [pyalm.config.PLOS_KEY_ENVVAR, pyalm.config.ELIFE_KEY_ENVVAR, pyalm.config.CROSSREF_KEY_ENVVAR, pyalm.config.PKP_KEY_ENVVAR, pyalm.config.COPERNICUS_KEY_ENVVAR, pyalm.config.PENSOFT_KEY_ENVVAR, pyalm.config.PLOS_URL_ENVVAR, pyalm.config.ELIFE_URL_ENVVAR, pyalm.config.CROSSREF_URL_ENVVAR, pyalm.config.PKP_URL_ENVVAR, pyalm.config.COPERNICUS_URL_ENVVAR, pyalm.config.PENSOFT_URL_ENVVAR] keydict = {} for x in kk: keydict[x] = os.environ.get(x) mdict = {} mdict['plos'] = {} mdict['elife'] = {} mdict['pkp'] = {} mdict['pensoft'] = {} mdict['crossref'] = {} mdict['copernicus'] = {} names = ['plos','elife','pkp','pensoft','crossref','copernicus'] for x in names: _insert_items(keydict, mdict, x) return mdict def _attempt_key_load(): """ This function (which will be auto-called on import of :mod:`pyalm`), will attempt to pull the API Keys from a few places. .. note:: This function is implemented to let the enviroment variable override the file read key. Keep this in mind when debugging silly issues. """ try: fp = os.path.expanduser(pyalm.config.PYALM_LOCATION) fd = open(fp, 'r') vals = fd.read().splitlines() pyalm.config.APIS = dict(iter([i.split("=") for i in vals])) except IOError as e: if e.errno != 2: warnings.warn('pyalm file %s exists but could not be opened: %s' % ( pyalm.config.PYALM_LOCATION, str(e))) try: pyalm.config.APIS = _get_env_vars() except KeyError as e: pass _attempt_key_load()
9ed440681c02ccd6939a93d40df0836095c3b8a2
[ "Markdown", "Python" ]
15
Python
lagotto/pyalm
3d4df6acf6215c0512afb4564d50a1c77b088380
2afda29691a71d525b6148a128185de6bc056b9d
refs/heads/master
<file_sep>import java.awt.*; import javax.swing.*; public class Cube extends JFrame{ //public class Cube { static Corner wgo; static Corner wbo; static Corner wbr; static Corner wgr; static Corner ygo; static Corner ybo; static Corner ybr; static Corner ygr; static JFrame frame; static Display d; public static void main(String[] args) { wgo = new Corner(-1,1,1,Color.ORANGE,Color.WHITE,Color.GREEN, "wgo"); wbo = new Corner(-1,1,-1,Color.ORANGE,Color.WHITE,Color.BLUE, "wbo"); wbr = new Corner(1,1,-1,Color.RED,Color.WHITE,Color.BLUE, "wbr"); wgr = new Corner(1,1,1,Color.RED,Color.WHITE,Color.GREEN, "wgr"); ygo = new Corner(-1,-1,1,Color.ORANGE,Color.YELLOW,Color.GREEN, "ygo"); ybo = new Corner(-1,-1,-1,Color.ORANGE,Color.YELLOW,Color.BLUE, "ybo"); ybr = new Corner(1,-1,-1,Color.RED,Color.YELLOW,Color.BLUE, "ybr"); ygr = new Corner(1,-1,1,Color.RED,Color.YELLOW,Color.GREEN, "ygr"); d = new Display(new Corner[] {wgo,wbo,wbr,wgr,ygo,ybo,ybr,ygr}); frame = new JFrame("VirtualTrainer"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(1000, 1000); frame.setFocusTraversalKeysEnabled(false); frame.add(d); frame.setVisible(true); } public void update() { frame.setVisible(false); frame.setVisible(true); } } <file_sep>import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.Arrays; import java.util.Random; import java.util.Scanner; import javax.swing.*; public class Display extends JPanel { private JButton scrambleButton; private int offset; private int boxLen; private RMove r; private LMove l; private UMove u; private DMove d; private FMove f; private BMove b; private RPrimeMove rp; private LPrimeMove lp; private UPrimeMove up; private DPrimeMove dp; private FPrimeMove fp; private BPrimeMove bp; private Corner wgo; private Corner wbo; private Corner wbr; private Corner wgr; private Corner ygo; private Corner ybo; private Corner ybr; private Corner ygr; private String key; private Corner[] corners; private Graphics2D g2d; private Color[] piece1; private Color[] piece2; private Color[] piece3; private Color[] piece4; private Color[] piece5; private Color[] piece8; private double magnifier; private TempDisplayCube rearrange; private GrabAlg ga = new GrabAlg(); public Display(Corner[] c) { wgo = c[0]; wbo = c[1]; wbr = c[2]; wgr = c[3]; ygo = c[4]; ybo = c[5]; ybr = c[6]; ygr = c[7]; corners = c; piece1 = c[0].getColors(); piece2 = c[1].getColors(); piece3 = c[2].getColors(); piece4 = c[3].getColors(); piece5 = c[4].getColors(); piece8 = c[7].getColors(); rearrange = new TempDisplayCube(); scrambleButton = new JButton("New Scramble"); scrambleButton.setFont(new Font("TimesRoman", Font.PLAIN, 50)); scrambleButton.setHorizontalTextPosition(AbstractButton.CENTER); scrambleButton.setRequestFocusEnabled(false); add(scrambleButton); setFocusTraversalKeysEnabled(false); setFocusable(true); requestFocusInWindow(); KeyListening kl = new KeyListening(); addKeyListener(kl); } public void paintComponent(Graphics g) { super.paintComponent(g); setSize(1000,1000); g2d = (Graphics2D)g; offset = 100; magnifier = 1; boxLen = (int)(100*magnifier); g2d.setColor(piece2[1]); g2d.fillRect(offset, offset, boxLen, boxLen); g2d.setColor(piece3[1]); g2d.fillRect(offset+ boxLen, offset, boxLen, boxLen); g2d.setColor(piece1[1]); g2d.fillRect(offset, offset + boxLen, boxLen, boxLen); g2d.setColor(piece4[1]); g2d.fillRect(offset + boxLen, offset + boxLen, boxLen, boxLen); g2d.setColor(piece2[2]); g2d.fillRect(offset, offset-10, boxLen, 10); g2d.setColor(piece3[2]); g2d.fillRect(offset + boxLen, offset-10, boxLen, 10); g2d.setColor(piece2[0]); g2d.fillRect(offset-10, offset, 10, boxLen); g2d.setColor(piece1[0]); g2d.fillRect(offset -10, offset + boxLen, 10, boxLen); g2d.setColor(piece5[1]); g2d.fillRect(offset, offset + 4*boxLen +10, boxLen, 10); g2d.setColor(piece8[1]); g2d.fillRect(offset + boxLen, offset + 4*boxLen + 10, boxLen, 10); g2d.setColor(piece1[0]); g2d.fillRect(offset-10, offset + 2*boxLen, 10, boxLen); g2d.setColor(piece5[0]); g2d.fillRect(offset -10, offset + 3*boxLen, 10, boxLen); g2d.setColor(piece1[2]); g2d.fillRect(offset, offset + 2*boxLen, boxLen, boxLen); g2d.setColor(piece4[2]); g2d.fillRect(offset+ boxLen, offset + 2*boxLen, boxLen, boxLen); g2d.setColor(piece5[2]); g2d.fillRect(offset, offset + 3*boxLen, boxLen, boxLen); g2d.setColor(piece8[2]); g2d.fillRect(offset + boxLen, offset + 3*boxLen, boxLen, boxLen); g2d.setColor(piece3[0]); g2d.fillRect(offset + 2*boxLen, offset, 10, boxLen); g2d.setColor(piece4[0]); g2d.fillRect(offset + 2*boxLen, offset + boxLen, 10, boxLen); g2d.setColor(piece4[0]); g2d.fillRect(offset + 2*boxLen, offset + 2*boxLen, 10, boxLen); g2d.setColor(piece8[0]); g2d.fillRect(offset + 2*boxLen, offset + 3*boxLen, 10, boxLen); } public void update(Corner[] c, boolean check){ wgo = c[0]; wbo = c[1]; wbr = c[2]; wgr = c[3]; ygo = c[4]; ybo = c[5]; ybr = c[6]; ygr = c[7]; corners = c; piece1 = c[0].getColors(); piece2 = c[1].getColors(); piece3 = c[2].getColors(); piece4 = c[3].getColors(); piece5 = c[4].getColors(); piece8 = c[7].getColors(); g2d.setColor(piece2[1]); g2d.fillRect(offset, offset, boxLen, boxLen); g2d.setColor(piece3[1]); g2d.fillRect(offset+ boxLen, offset, boxLen, boxLen); g2d.setColor(piece1[1]); g2d.fillRect(offset, offset + boxLen, boxLen, boxLen); g2d.setColor(piece4[1]); g2d.fillRect(offset + boxLen, offset + boxLen, boxLen, boxLen); g2d.setColor(piece2[2]); g2d.fillRect(offset, offset-10, boxLen, 10); g2d.setColor(piece3[2]); g2d.fillRect(offset + boxLen, offset-10, boxLen, 10); g2d.setColor(piece2[0]); g2d.fillRect(offset-10, offset, 10, boxLen); g2d.setColor(piece1[0]); g2d.fillRect(offset -10, offset + boxLen, 10, boxLen); g2d.setColor(piece1[2]); g2d.fillRect(offset, offset + 2*boxLen, boxLen, boxLen); g2d.setColor(piece4[2]); g2d.fillRect(offset+ boxLen, offset + 2*boxLen, boxLen, boxLen); g2d.setColor(piece5[2]); g2d.fillRect(offset, offset + 3*boxLen, boxLen, boxLen); g2d.setColor(piece8[2]); g2d.fillRect(offset + boxLen, offset + 3*boxLen, boxLen, boxLen); g2d.setColor(piece5[1]); g2d.fillRect(offset, offset + 4*boxLen +10, boxLen, 10); g2d.setColor(piece8[1]); g2d.fillRect(offset + boxLen, offset + 4*boxLen + 10, boxLen, 10); g2d.setColor(piece1[0]); g2d.fillRect(offset-10, offset + 2*boxLen, 10, boxLen); g2d.setColor(piece5[0]); g2d.fillRect(offset -10, offset + 3*boxLen, 10, boxLen); g2d.setColor(piece3[0]); g2d.fillRect(offset + 2*boxLen, offset, 10, boxLen); g2d.setColor(piece4[0]); g2d.fillRect(offset + 2*boxLen, offset + boxLen, 10, boxLen); g2d.setColor(piece4[0]); g2d.fillRect(offset + 2*boxLen, offset + 2*boxLen, 10, boxLen); g2d.setColor(piece8[0]); g2d.fillRect(offset + 2*boxLen, offset + 3*boxLen, 10, boxLen); revalidate(); repaint(); if (check) {checkSolved(); System.out.println("checked");}else {System.out.println("Not checked");} } public void scramble() { ReadAlgorithm ra = new ReadAlgorithm(); ga.openFile("scrams1.txt"); ga.readFileFirst(); ga.closeFile(); ga.openFile("scrams1.txt"); String[][] list = ga.readFileSecond(); // ga.closeFile(); Random r = new Random(); int randInt = r.nextInt(list.length); String[] moves = list[randInt]; corners = ra.execute(corners, moves); corners = rearrange.rearrange(corners); update(corners, false); System.out.println("Scrambled"); } public void checkSolved(){ corners = rearrange.rearrange(corners); Corner[] uFace = new Corner[] {corners[0], corners[1], corners[2], corners[3]}; Corner[] dFace = new Corner[] {corners[4], corners[5], corners[6], corners[7]}; Corner[] fFace = new Corner[] {corners[0], corners[3], corners[4], corners[7]}; Corner[] bFace = new Corner[] {corners[1], corners[2], corners[5], corners[6]}; Corner[] rFace = new Corner[] {corners[2], corners[3], corners[6], corners[7]}; int matches = 0; int solvedFaces = 0; for(Corner testColors: uFace) { if(testColors.getColors()[1]==uFace[0].getColors()[1]) {matches++;} } if (matches==4) {solvedFaces++;} matches = 0; for(Corner testColors: dFace) { if(testColors.getColors()[1]==dFace[0].getColors()[1]) {matches++;} } if (matches==4) {solvedFaces++;} matches = 0; for(Corner testColors: fFace) { if(testColors.getColors()[2]==fFace[0].getColors()[2]) {matches++;} } if (matches==4) {solvedFaces++;} matches = 0; for(Corner testColors: bFace) { if(testColors.getColors()[2]==bFace[0].getColors()[2]) {matches++;} } if (matches==4) {solvedFaces++;} matches = 0; for(Corner testColors: rFace) { if(testColors.getColors()[0]==rFace[0].getColors()[0]) {matches++;} } if (matches==4) {solvedFaces++;} if(solvedFaces==5) { scramble(); System.out.println("solved"); } } private class KeyListening implements KeyListener{ boolean pressed = false; public void keyTyped(KeyEvent e) { } public void keyPressed(KeyEvent e) { { pressed = true; int key = e.getKeyCode(); switch(key) { case 73: for(int x = 0; x < corners.length; x++) { r = new RMove(corners[x]); if(r.check()) {corners[x] = r.move();} } break; case 75: for(int x = 0; x < corners.length; x++) { rp = new RPrimeMove(corners[x]); if(rp.check()) {corners[x] = rp.move();} } break; case 68: for(int x = 0; x < corners.length; x++) { l = new LMove(corners[x]); if(l.check()) {corners[x] = l.move();} } break; case 69: for(int x = 0; x < corners.length; x++) { lp = new LPrimeMove(corners[x]); if(lp.check()) {corners[x] = lp.move();} } break; case 74: for(int x = 0; x < corners.length; x++) { u = new UMove(corners[x]); if(u.check()) {corners[x] = u.move();} } break; case 70: for(int x = 0; x < corners.length; x++) { up = new UPrimeMove(corners[x]); if(up.check()) {corners[x] = up.move();} } break; case 76: for(int x = 0; x < corners.length; x++) { dp = new DPrimeMove(corners[x]); if(dp.check()) {corners[x] = dp.move();} } break; case 83: for(int x = 0; x < corners.length; x++) { d = new DMove(corners[x]); if(d.check()) {corners[x] = d.move();} } break; case 71: for(int x = 0; x < corners.length; x++) { fp = new FPrimeMove(corners[x]); if(fp.check()) {corners[x] = fp.move();} } break; case 72: for(int x = 0; x < corners.length; x++) { f = new FMove(corners[x]); if(f.check()) {corners[x] = f.move();} } break; case 87: for(int x = 0; x < corners.length; x++) { b = new BMove(corners[x]); if(b.check()) {corners[x] = b.move();} } break; case 79: for(int x = 0; x < corners.length; x++) { bp = new BPrimeMove(corners[x]); if(bp.check()) {corners[x] = bp.move();} } break; } corners = rearrange.rearrange(corners); update(rearrange.rearrange(corners), true); } } public void keyReleased(KeyEvent e) { pressed = false; } } } <file_sep>import java.awt.*; /** * Write a description of class Corner here. * * @Will_Callan * @1.0 */ public class Corner { Color[] pieceColors; int[] pieceCoords; String name; /* * initializes colors and coordinates of the piece */ Corner(int x, int y, int z, Color cx, Color cy, Color cz, String n) { pieceColors = new Color[]{cx, cy, cz}; pieceCoords = new int[] {x,y,z}; name = n; } public void setCoords(int[] newCoords) { pieceCoords = newCoords; } public void setColors(Color[] newColors) { pieceColors = newColors; } public int[] getCoords() { return pieceCoords; } public Color[] getColors() { return pieceColors; } public String getName() { return name; } }
cef9a7e3aa0da81ddec13f747f8467c4f2205284
[ "Java" ]
3
Java
WAC4173/Programs
0bec36c31ef90f968ea787da3a741076c5bf619f
1e4f09b27ccfcb75a2edb52241673b8161c8d3e1
refs/heads/master
<repo_name>artisdom/nix-prefix<file_sep>/bin/check-nss.py #!/usr/bin/env python import os import pwd print pwd.getpwuid(os.getuid()) <file_sep>/bin/update-glibc-hack.sh #!/usr/bin/env bash python=$(nix-build -A python $NIXPKGS)/bin/python $python ./bin/check-nss.py set -e (cd nixpkgs/ git reset --hard remotes/origin/master git fetch origin pull/14697/head:sssd git cherry-pick \ 1f4f0e71f39ab2e10602c2e70e45065b8475f8de \ 3b1e666a3fc3d30404f095e4c0764b305a9fe2bd \ d57d7ba9e7084328be3392464efbaaf8b66c1f7f \ 6379645543d9aed4eb696efc276691f17ac18f11 \ 3453451f39849e9cfb0f210848b5119bc9f93d0a \ 2c0351afea2eb0016de7358975740b23fdc6701c ) nix-env -i sssd -f $NIXPKGS nixdir=$(nix-build $NIXPKGS -A glibc.out)/lib chmod 777 $nixdir libnss=$(find ../nix -name libnss_sss.so.\* | grep sssd) echo $libnss cp -f $libnss $nixdir/ chmod 555 $nixdir $python ./bin/check-nss.py <file_sep>/etc/nix-install.sh #!/bin/bash set -e base=$1 shift; export nix_boot=${NIX_BOOT-$base/nix-boot/usr} export nix_root=${NIX_ROOT-$base/nix} export nix_bin=$nix_root/var/nix/profiles/default/bin export RUN_EXPENSIVE_TESTS=no export PATH=$nix_boot/bin:/usr/bin:/bin # wiki export PKG_CONFIG_PATH=$nix_boot/lib/pkgconfig:$PKG_CONFIG_PATH # wiki export LDFLAGS="-L$nix_boot/lib -L$nix_boot/lib64 $LDFLAGS" # wiki export CPPFLAGS="-I$nix_boot/include $CPPFLAGS" # wiki export PERL5OPT="-I$nix_boot/lib/perl" # wiki #export PERL5OPT="-I$nix_boot/lib64/perl5" # wiki on some systems. export NIXPKGS=$base/nix-boot/nixpkgs unset PERL5LIB PERL_LOCAL_LIB_ROOT PERL_MB_OPT PERL_MM_OPT # Perl INSTALLBASE error. all="get prepare nixpkgs\ gcc \ bzip2 \ curl \ sqlite \ dbi \ dbd \ wwwcurl \ bison \ flex \ coreutils \ nixbootstrap nix nixconfig nixprofile" get() { # remove echo to download. echo wget -c $1 } case $1 in -h) echo $all; exit 0;; get) mkdir -p src (cd ./static; files="https://nixos.org/releases/nix/nix-1.10/nix-1.10.tar.xz http://bzip.org/1.0.6/bzip2-1.0.6.tar.gz http://curl.haxx.se/download/curl-7.35.0.tar.lzma https://www.sqlite.org/2014/sqlite-autoconf-3080300.tar.gz http://pkgs.fedoraproject.org/repo/extras/perl-DBI/DBI-1.631.tar.gz/444d3c305e86597e11092b517794a840/DBI-1.631.tar.gz http://pkgs.fedoraproject.org/repo/pkgs/perl-DBD-SQLite/DBD-SQLite-1.40.tar.gz/b9876882186499583428b14cf5c0e29c/DBD-SQLite-1.40.tar.gz http://search.cpan.org/CPAN/authors/id/S/SZ/SZBALINT/WWW-Curl-4.15.tar.gz http://ftp.gnu.org/gnu/bison/bison-3.0.4.tar.gz http://sourceforge.mirrorservice.org/f/fl/flex/flex-2.5.36.tar.gz https://ftp.gnu.org/gnu/gcc/gcc-4.9.2/gcc-4.9.2.tar.gz http://ftp.gnu.org/gnu/coreutils/coreutils-8.23.tar.xz" for i in $files; do y=$(echo $i | sed -e 's#.*/##g') get -c $i; case $i in *xz) xzcat $y;; *gz) zcat $y;; *lzma) xzcat $y;; *tar) cat $y;; *) cat $y;; esac | (cd ../src && tar -xvpf -) done ) ;; -sh) ( export LD_LIBRARY_PATH="$nix_boot/lib:$nix_boot/lib64:$LD_LIBRARY_PATH"; $2; ); exit 0;; bzip2) (cd src/bzip2-1.0.6; make -f Makefile-libbz2_so; make install PREFIX=$nix_boot; cp libbz2.so.1.0 libbz2.so.1.0.6 $nix_boot/lib; ) ;; curl) (cd src/curl-7.35.0/; ./configure --prefix=$nix_boot; make; make install; ) ;; sqlite) (cd src/sqlite-autoconf-3080300/; ./configure --prefix=$nix_boot; make; make install; ) ;; libxml2) (cd src/libxml2-2.9.2; ./configure --prefix=$nix_boot; make; cp ./libxml2-2.9.2/xmllint $nix_boot/bin # make install; ) ;; libxslt) (cd src/libxslt-1.1.28; ./configure --prefix=$nix_boot; make; make install; ) ;; gcc) (cd src/gcc-4.9.2; ./contrib/download_prerequisites; ) rm -rf src/gcc-objs; mkdir -p src/gcc-objs (cd src/gcc-objs; ./../gcc-4.9.2/configure --prefix=$nix_boot --disable-multilib; make; make install; ) ;; bison) (cd src/bison-3.0*; ./configure --prefix=$nix_boot; make; make install; ) ;; flex) (cd src/flex-2.5.*; ./configure --prefix=$nix_boot; make; make install; );; coreutils) (cd src/coreutils-8.23; ./configure --enable-install-program=hostname --prefix=$nix_boot; make; make install; );; bash) (cd src/bash-4.3; ./configure --prefix=$nix_boot; make; make install; );; dbi) (cd src/DBI-1.631/; echo perl Makefile.PL PREFIX=$nix_boot PERLMAINCC=$nix_boot/bin/gcc > myconfig.sh; chmod +x myconfig.sh; ./myconfig.sh; make; make install; ) ;; dbd) (cd src/DBD-SQLite-1.40/; echo perl Makefile.PL PREFIX=$nix_boot PERLMAINCC=$nix_boot/bin/gcc > myconfig.sh; chmod +x myconfig.sh; ./myconfig.sh; make; make install; ) ;; wwwcurl) (cd src/WWW-Curl-4.15; echo perl Makefile.PL PREFIX=$nix_boot PERLMAINCC=$nix_boot/bin/gcc > myconfig.sh; chmod +x myconfig.sh; ./myconfig.sh; make; make install; ) ;; prepare) rm -rf nix rm -rf $NIXPKGS rm -rf ~/.nix-profile git clone https://github.com/NixOS/nix nix ;; nixpkgs) git clone <EMAIL>:NixOS/nixpkgs.git $NIXPKGS (cd $NIXPKGS && cat ~/.home/non-nix.patch | patch -p1 ) ;; nixbootstrap) (cd nix; ./bootstrap.sh ) ;; nix) (cd nix; echo "./configure --prefix=$nix_boot \ --with-store-dir=$nix_root/store \ --localstatedir=$nix_root/var" > myconfig.sh; chmod +x ./myconfig.sh ./myconfig.sh # --with-coreutils-bin=$nix_boot/usr/bin; /usr/bin/perl -pi -e 's#--nonet# #g' doc/manual/local.mk; echo "GLOBAL_LDFLAGS += -lpthread" >> doc/manual/local.mk; make; make install; ) ;; nixconfig) ( export LD_LIBRARY_PATH="$nix_boot/lib:$nix_boot/lib64:$LD_LIBRARY_PATH"; echo $LD_LIBRARY_PATH; # nix-channel --add http://nixos.org/channels/nixpkgs-unstable && \ # nix-channel --update && # nix-env -i nix # $nix_boot/bin/nix-env -i nix-1.12pre4523_3b81b26 -f $NIXPKGS $nix_boot/bin/nix-env -iA nixUnstable -f $NIXPKGS ) echo recheck $nix_root/var/nix/profiles/default/bin/nix-env -iA nixUnstable ;; nixprofile) ln -s $nix_root/var/nix/profiles/default $HOME/.nix-profile ;; all) echo all for i in $all; do env nix_boot=$nix_boot nix_root=$nix_root ./$0 $base $i ; done ;; *) echo $0 '<install-base>' all echo $all; echo nix_root=$nix_root echo nix_boot=$nix_boot echo PATH=$PATH echo PKG_CONFIG_PATH=$PKG_CONFIG_PATH echo LDFLAGS=$LDFLAGS echo CPPFLAGS=$CPPFLAGS echo PERL5OPT=$PERL5OPT echo NIXPKGS=$NIXPKGS ;; esac <file_sep>/Makefile base=/scratch/gopinatr nix_pre=$(base)/nix-prefix nix_boot_usr=$(nix_pre)/usr NIXPKGS=$(nix_pre)/nixpkgs nixpkgs_config=~/.nixpkgs/ nixprofile=~/.nix-profile NIXPKGS_CONFIG=$(HOME)/.nixpkgs/config.nix nix_root=$(base)/nix nix_store=$(nix_root)/store nix_var=$(nix_root)/var nix_bin=$(nix_root)/var/nix/profiles/default/bin logit= >> logs 2>&1 #@ nix=https://nixos.org/releases/nix/nix-1.10/nix-1.10.tar.xz #@ bzip2=http://bzip.org/1.0.6/bzip2-1.0.6.tar.gz #@ curl=https://curl.haxx.se/download/curl-7.35.0.tar.lzma #@ sqlite=https://www.sqlite.org/2014/sqlite-autoconf-3080300.tar.gz #@ dbi=http://pkgs.fedoraproject.org/repo/extras/perl-DBI/DBI-1.631.tar.gz/444d3c305e86597e11092b517794a840/DBI-1.631.tar.gz #@ dbd=http://pkgs.fedoraproject.org/repo/pkgs/perl-DBD-SQLite/DBD-SQLite-1.40.tar.gz/b9876882186499583428b14cf5c0e29c/DBD-SQLite-1.40.tar.gz #@ wwwcurl=http://search.cpan.org/CPAN/authors/id/S/SZ/SZBALINT/WWW-Curl-4.15.tar.gz #@ bison=http://ftp.gnu.org/gnu/bison/bison-3.0.4.tar.gz #@ flex=http://sourceforge.mirrorservice.org/f/fl/flex/flex-2.5.36.tar.gz #@ gcc=https://ftp.gnu.org/gnu/gcc/gcc-4.9.2/gcc-4.9.2.tar.gz #@ coreutils=http://ftp.gnu.org/gnu/coreutils/coreutils-8.23.tar.xz #@ file=ftp://ftp.astron.com/pub/file/file-5.27.tar.gz src_build=./configure --prefix=$(nix_boot_usr) && make && make install perl_build=echo unset PERL5LIB PERL_LOCAL_LIB_ROOT PERL_MB_OPT PERL_MM_OPT > myconfig.sh && \ echo perl Makefile.PL PREFIX=$(nix_boot_usr) PERLMAINCC=$(nix_boot_usr)/bin/gcc >> myconfig.sh && \ chmod +x myconfig.sh && ./myconfig.sh && make && make install; src=nix \ bzip2 \ curl \ sqlite \ dbi \ dbd \ wwwcurl \ bison \ flex \ gcc \ coreutils .PHONY: get build nix all: nix @echo done $^. get: $(addsuffix .x,$(addprefix static/,$(src))) @echo done $^ extract: $(addsuffix .x/.extracted,$(addprefix build/,$(src))) @echo done $^ static/%.x: | static curl -C - -L $$(cat $(MAKEFILE_LIST) | sed -ne '/^#@ $*=/s/^[^=]*=//p') -o [email protected] mv [email protected] $@ build/%/.extracted: static/% build/file.x/.build mkdir -p build/$* export PATH=$(nix_boot_usr)/bin:/usr/bin:/bin && \ case "$$(file static/$* | sed -e 's#^[^:]*: *##')" in \ gzip*) zcat "$<";; \ XZ*) xzcat "$<";; \ LZMA*) xzcat "$<";; \ *) cat "$*";; \ esac | (cd build/$* && tar -xpf -) touch $@ build/nix.x/.extracted: rm -rf build/nix.x && mkdir -p build/nix.x cd build/nix.x && git clone https://github.com/NixOS/nix nix touch $@ build/file.x/.build: build/file.x/.extracted (cd $(@D)/* && $(src_build) ) $(logit) touch $@ build/curl.x/.build: build/curl.x/.extracted (cd $(@D)/* && $(src_build) ) $(logit) touch $@ build/sqlite.x/.build: build/sqlite.x/.extracted (cd $(@D)/* && $(src_build) ) $(logit) touch $@ build/libxslt.x/.build: build/libxslt.x/.extracted (cd $(@D)/* && $(src_build) ) $(logit) touch $@ build/bison.x/.build: build/bison.x/.extracted (cd $(@D)/* && $(src_build) ) $(logit) touch $@ build/flex.x/.build: build/flex.x/.extracted (cd $(@D)/* && $(src_build) ) $(logit) touch $@ build/bash.x/.build: build/bash.x/.extracted (cd $(@D)/* && $(src_build) ) $(logit) touch $@ build/bzip2.x/.build: build/bzip2.x/.extracted (cd $(@D)/* && \ make -f Makefile-libbz2_so && make install PREFIX=$(nix_boot_usr) && \ cp libbz2.so.* $(nix_boot_usr)/lib; ) $(logit) touch $@ build/libxml2.x/.build: build/libxml2.x/.extracted (cd $(@D)/* && \ ./configure --prefix=$(nix_boot_usr) && make \ cp ./libxml2-2.9.2/xmllint $(nix_boot_usr)/bin ) $(logit) touch $@ build/gcc.x/.build: build/gcc.x/.extracted (cd $(@D)/* && \ rm -rf gcc-objs && mkdir -p gcc-objs && \ ./contrib/download_prerequisites; ) $(logit) (cd build/gcc.x/*/gcc-objs; ../configure --prefix=$(nix_boot_usr) --disable-multilib && make && make install; ) $(logit) touch $@ build/coreutils.x/.build: build/coreutils.x/.extracted (cd $(@D)/* && \ ./configure --enable-install-program=hostname --prefix=$(nix_boot_usr) && make && make install; ) $(logit) touch $@ build/dbi.x/.build: build/dbi.x/.extracted (cd $(@D)/* && $(perl_build)) $(logit) touch $@ build/dbd.x/.build: build/dbd.x/.extracted (cd $(@D)/* && $(perl_build)) $(logit) touch $@ build/wwwcurl.x/.build: build/wwwcurl.x/.extracted (cd $(@D)/* && $(perl_build)) $(logit) touch $@ build/nix.x/.build: build/nix.x/.extracted $(addprefix build/,$(addsuffix .x/.build, $(filter-out nix,$(src)))) (cd $(@D)/* && \ echo "./configure --prefix=$(nix_boot_usr) --with-store-dir=$(nix_store) --localstatedir=$(nix_var)" > myconfig.sh && \ chmod +x ./myconfig.sh && \ /usr/bin/perl -pi -e 's#--nonet# #g' doc/manual/local.mk && \ unset PERL5LIB PERL_LOCAL_LIB_ROOT PERL_MB_OPT PERL_MM_OPT && \ echo "GLOBAL_LDFLAGS += -lpthread" >> doc/manual/local.mk && \ export PATH=$(nix_boot_usr)/bin:/usr/bin:/bin && \ export PKG_CONFIG_PATH=$(nix_boot_usr)/lib/pkgconfig:$(PKG_CONFIG_PATH) && \ export LDFLAGS="-L$(nix_boot_usr)/lib -L$(nix_boot_usr)/lib64 $(LDFLAGS)" && \ export CPPFLAGS="-I$(nix_boot_usr)/include $(CPPFLAGS)" &&\ export PERL5OPT="-I$(nix_boot_usr)/lib/perl" && \ export NIXPKGS=$(NIXPKGS) && \ ./bootstrap.sh && ./myconfig.sh && make && make install; ) $(logit) touch $@ build: $(addprefix build/,$(addsuffix .x/.build,$(src))) @echo done $@ # set NIXPKGS_CONFIG $(nixpkgs_config)/config.nix: mkdir -p $(nixpkgs_config) cat etc/config.nix | sed -e 's#BASE#$(base)#g' > $(nixpkgs_config)/config.nix build/.nixconfig: $(addprefix build/,$(addsuffix .x/.build,$(src))) build/.nixpkgs $(nixpkgs_config)/config.nix env LD_LIBRARY_PATH="$(nix_boot_usr)/lib:$(nix_boot_usr)/lib64" \ $(nix_boot_usr)/bin/nix-env -iA nixUnstable -f $(NIXPKGS) touch $@ build/.nixpkgs: $(addprefix build/,$(addsuffix .x/.build,$(src))) build/.pkgcheckout touch $@ build/.pkgcheckout: rm -rf $(NIXPKGS) git clone [email protected]:NixOS/nixpkgs.git $(NIXPKGS) cat etc/non-nix.patch | (cd $(NIXPKGS) && patch -p1 ) mkdir -p build/ touch $@ nixcheckout: build/.pkgcheckout @echo done nixconfig: build/.nixconfig echo done $^ $(nixprofile): ln -s $(nix_root)/var/nix/profiles/default $(nixprofile) nixprofile: rm -rf $(nixprofile) ln -s $(nix_root)/var/nix/profiles/default $(nixprofile) static: ; mkdir -p $@ finish: ; rm -rf build usr logs clean: ; rm -rf build logs clobber: rm -rf build static src $(NIXPKGS) $(nix_boot_usr) nix logs -chmod -R 777 $(nix_root) && rm -rf $(nix_root) link: ln -s etc/Makefile.nix Makefile channel: rm -rf $(HOME)/.nix-defexpr/* cd $(HOME)/.nix-defexpr/; ln -s $(NIXPKGS) . nix: build/.nixpkgs build/.nixconfig @echo done $^ <file_sep>/bin/update-perms.sh find ../nix -perm 600 | while read a ; do chmod 660 $a; done find ../nix -perm 644 | while read a ; do chmod 664 $a; done find ../nix -perm 755 | while read a ; do chmod 775 $a; done <file_sep>/bin/remove-glibc-hack.sh #!/usr/bin/env bash set -e python=$(nix-build -A python $NIXPKGS)/bin/python $python ./bin/check-nss.py nixdir=$(nix-build $NIXPKGS -A glibc.out)/lib chmod 777 $nixdir #libnss=$(find ../nix -name libnss_sss.so.\* | grep sssd) #echo $libnss #cp -f $libnss $nixdir/ rm $nixdir/libnss_sss.so.* chmod 555 $nixdir $python ./bin/check-nss.py <file_sep>/bin/nix.sh export PATH=$HOME/.nix-profile/bin:$PATH export NIXDIR=/scratch/gopinatr/nix-prefix export NIXPKGS=$NIXDIR/nixpkgs/ export NIX_PATH=$NIXPKGS:nixpkgs=$NIXPKGS export PS1='nix> ' bash
cc88ce60e55f073e91252a0419e937bb790b26a3
[ "Python", "Makefile", "Shell" ]
7
Python
artisdom/nix-prefix
a5c44d4f700fabfb498407c234d64c844850b029
1faeb65a3077030426dc1fe1a03231974ddb1d9b
refs/heads/master
<repo_name>weal1312/image<file_sep>/image.py import argparse import os from PIL import Image class IMG: def __init__(self, source_path, dest_dir): self.img = Image.open(source_path) self.width, self.height = self.img.size self.dest_dir = dest_dir self.filename = os.path.basename(source_path) def crop(self): dest_height = self.width / 3 * 4 margin_y = (self.height - dest_height) / 2 region = self.img.crop((0, margin_y, self.width, dest_height + margin_y)) region.save(os.path.join(self.dest_dir, self.filename)) def split(self): dest_width = self.width / 2 img_l = self.img.crop((0, 0, dest_width, self.height)) img_r = self.img.crop((dest_width, 0, self.width, self.height)) img_l.save(os.path.join(self.dest_dir, self.filename + '_2.png')) img_r.save(os.path.join(self.dest_dir, self.filename + '_1.png')) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('mod', help='define the type image process(crop|split)') parser.add_argument('-i', '--input', help='define the input path') parser.add_argument('-o', '--output', help='define the output path') args = parser.parse_args() method = args.mod source_dir = args.input if args.input else 'E:\\Downloads\\temp' dest_dir = args.output if args.output else os.path.join(source_dir, 'output') os.makedirs(dest_dir, exist_ok=True) for path in [os.path.join(source_dir, file) for file in os.listdir(source_dir) if file.endswith('png')]: getattr(IMG(path, dest_dir), method)()<file_sep>/README.md # image crop or split the images which in destination directory. usage: main.py [-h] [-i INPUT] [-o OUTPUT] mod positional arguments: mod define the type image process(crop or split) optional arguments: -h, --help show this help message and exit -i INPUT, --input INPUT define the input path -o OUTPUT, --output OUTPUT define the output path
c811e37d51d29b9b97dce7a96e6945f8ee9d9b0f
[ "Markdown", "Python" ]
2
Python
weal1312/image
284d2bae28242db2f6f1b73a9deafeb57e112261
224e51c88d3059d6288a2ef59eea57dbfbe398dd
refs/heads/master
<repo_name>rajesh6927/php-coding-standards<file_sep>/.php_cs.dist <?php declare(strict_types=1); use Mollie\PhpCodingStandards\PhpCsFixer\Rules; use PhpCsFixer\Config; use PhpCsFixer\Finder; $finder = Finder::create() ->name('.php_cs.dist') // Fix this file as well ->in(__DIR__); $overrides = [ 'declare_strict_types' => true, ]; return Config::create() ->setFinder($finder) ->setRiskyAllowed(true) ->setRules(Rules::getForPhp71($overrides));
f0b0f7fde3a427bf5ee0f9e02073f70e42e1fcc7
[ "PHP" ]
1
PHP
rajesh6927/php-coding-standards
9b2bb6cabac9462068baf7cb25a2b45cfe9abf28
0c3eca7bb3fae7f440c09d84ecdbeaed89129096
refs/heads/master
<repo_name>wang-yang/cell_signalling_analysis<file_sep>/src/odps/odps-console-dist-public/odps_config.ini project_name= access_id= access_key= end_point= tunnel_endpoint= log_view_host= https_check= # confirm threshold for query input size(unit: GB) data_size_confirm= <file_sep>/src/api_platform/api_platform.py #-*- coding:utf-8 –*- import os.path import subprocess import shlex import multiprocessing import datetime import time from pymongo import MongoClient from odps import ODPS import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web from tornado.escape import json_encode from tornado.options import define, options define("port", default=8000, help="run on the given port", type=int) # Make odps client configurable #_odps_client = "/Users/willwywang-NB/"+\ # "github/cell_signalling_analysis/tool/odps/bin/odpscmd" _project_home = os.path.dirname(os.path.realpath(__file__)) print("Project Home: " + _project_home) _odps_client = _project_home + "/../../tool/odps/bin/odpscmd" print("ODPS Client: " + _odps_client) # 定义见文档: 任务进度查询.md _task_id = {"create_customer_raw_data_table":1, "upload_customer_raw_data":2, "transform_to_spatio_temporal_raw_data":3, "compute_raw_data_stat":4, "compute_people_distribution":5, "compute_base_station_info":6, "download_base_station_info":7, "filter_data_with_range":8, "compute_filtered_data_stat":9, "compute_base_station_hour_summary":10, "download_base_station_hour_summary":11, "compute_uuid_cell_hour":12, "delete_all_tables":13, "compute_peo_roam":30, "compute_peo_type":31, "compute_uuid_od":32, "upload_area_station":33, "compute_business_data":34, "download_business_data":35 } _download_folder = _project_home + "/downloads" if not os.path.exists(_download_folder): os.makedirs(_download_folder) access_id = "xO0RtfYLVQEnAuUN" access_key = "<KEY>" project = "tsnav_project" end_point = "http://service.odps.aliyun.com/api" odps = ODPS(access_id, access_key, project, end_point) def plog(msg): print "API: ", msg class Application(tornado.web.Application): def __init__(self): handlers=[ (r'/', IndexHandler), (r'/test_create_customer_raw_data', # 1 TestCreateCustomerRawDataTableHandler), (r'/test_upload', # 2 TestUploadHandler), (r'/test_request_task_progress', # 3 TestRequestTaskProgressHandler), (r'/test_transform_to_inner_format', # 4 TestTransformToInnerFormatHandler), (r'/test_compute_raw_data_stat', # 5 TestComputeRawDataStatHandler), (r'/test_get_raw_data_stat', # 6 TestGetRawDataStatHandler), (r'/test_compute_people_distribution', # 7 TestComputePeopleDistributionHandler), (r'/test_get_people_distribution', # 8 TestGetPeopleDistributionHandler), (r'/test_compute_base_station_info', # 9 TestComputeBaseStationInfoHandler), (r'/test_download_base_station_info', # 10 TestDownloadBaseStationInfoHandler), (r'/test_get_base_station_info', # 11 TestGetBaseStationInfoHandler), (r'/test_filter_data_with_range', # 12 TestFilterDataWithRangeHandler), (r'/test_compute_filtered_data_stat', # 13 TestComputeFilteredDataStatHandler), (r'/test_get_filtered_data_stat', # 14 TestGetFilteredDataStatHandler), (r'/test_compute_base_station_hour_summary', # 15 TestComputeBaseStationHourSummaryHandler), (r'/test_download_base_station_hour_summary',# 16 TestDownloadBaseStationHourSummaryHandler), (r'/test_get_base_station_hour_summary', # 17 TestGetBaseStationHourSummaryHandler), (r'/test_compute_uuid_cell_hour', # 18 TestComputeUuidCellHourHandler), (r'/test_get_uuid_cell_hour', # 19 TestGetUuidCellHourHandler), (r'/test_delete_all_tables', # 20 TestDeleteAllTablesHandler), (r'/test_compute_peo_roam', # 30 TestComputePeopleRoamHandler), (r'/test_compute_peo_type', # 31 TestComputePeopleTypeHandler), (r'/test_compute_uuid_od', # 32 TestComputeODHandler), (r'/test_upload_area_station', # 33 TestUploadAreaStationHandler), (r'/test_compute_business_data', # 34 TestComputeBusinessDataHandler), (r'/test_download_business_data', # 35 TestDownloadBusinessDataHandler), (r'/create_customer_raw_data', # 1 CreateCustomerRawDataHandler), (r'/upload_data', # 2 UploadHandler), (r'/request_task_progress', # 3 RequestTaskProgressHandler), (r'/transform_to_inner_format', # 4 TransformToInnerFormatHandler), (r'/compute_raw_data_stat', # 5 ComputeRawDataStatHandler), (r'/get_raw_data_stat', # 6 GetRawDataStatHandler), (r'/compute_people_distribution', # 7 ComputePeopleDistributionHandler), (r'/get_people_distribution', # 8 GetPeopleDistributionHandler), (r'/compute_base_station_info', # 9 ComputeBaseStationInfoHandler), (r'/download_base_station_info', # 10 DownloadBaseStationInfoHandler), (r'/get_base_station_info', # 11 GetBaseStationInfoHandler), (r'/filter_data_with_range', # 12 FilterDataWithRangeHandler), (r'/compute_filtered_data_stat', # 13 ComputeFilteredDataStatHandler), (r'/get_filtered_data_stat', # 14 GetFilteredDataStatHandler), (r'/compute_base_station_hour_summary', # 15 ComputeBaseStationHourSummaryHandler), (r'/download_base_station_hour_summary', # 16 DownloadBaseStationHourSummaryHandler), (r'/get_base_station_hour_summary', # 17 GetBaseStationHourSummaryHandler), (r'/compute_uuid_cell_hour', # 18 ComputeUuidCellHourHandler), (r'/get_uuid_cell_hour', # 19 GetUuidCellHourHandler), (r'/delete_all_tables', # 20 DeleteAllTablesHandler), (r'/compute_peo_roam', # 30 ComputePeopleRoamHandler), (r'/compute_peo_type', # 31 ComputePeopleTypeHandler), (r'/compute_uuid_od', # 32 ComputeODHandler), (r'/upload_area_station', # 33 UploadCellAreaHandler), (r'/compute_business_data', # 34 ComputeBusinessDataHandler), (r'/download_business_data', # 35 DownloadBusinessDataHandler), ] settings = dict( template_path=os.path.join(os.path.dirname(__file__), "templates"), static_path=os.path.join(os.path.dirname(__file__), "static"), debug=True, ) tornado.web.Application.__init__(self, handlers, **settings) class IndexHandler(tornado.web.RequestHandler): def get(self): self.render('index.html') # 1 class TestCreateCustomerRawDataTableHandler(tornado.web.RequestHandler): def get(self): self.render('test_create_customer_raw_data_table.html') # 2 class TestUploadHandler(tornado.web.RequestHandler): def get(self): self.render('test_upload.html') # 3 class TestRequestTaskProgressHandler(tornado.web.RequestHandler): def get(self): self.render('test_request_task_progress.html') # 4 class TestTransformToInnerFormatHandler(tornado.web.RequestHandler): def get(self): self.render('test_transform_to_inner_format.html') # 5 class TestComputeRawDataStatHandler(tornado.web.RequestHandler): def get(self): self.render('test_compute_raw_data_stat.html') # 6 class TestGetRawDataStatHandler(tornado.web.RequestHandler): def get(self): self.render('test_get_raw_data_stat.html') # 7 class TestComputePeopleDistributionHandler(tornado.web.RequestHandler): def get(self): self.render('test_compute_people_distribution.html') # 8 class TestGetPeopleDistributionHandler(tornado.web.RequestHandler): def get(self): self.render('test_get_people_distribution.html') # 9 class TestComputeBaseStationInfoHandler(tornado.web.RequestHandler): def get(self): self.render('test_compute_base_station_info.html') # 10 class TestDownloadBaseStationInfoHandler(tornado.web.RequestHandler): def get(self): self.render('test_download_base_station_info.html') # 11 class TestGetBaseStationInfoHandler(tornado.web.RequestHandler): def get(self): self.render('test_get_base_station_info.html') # 12 class TestFilterDataWithRangeHandler(tornado.web.RequestHandler): def get(self): self.render('test_filter_data_with_range.html') # 13 class TestComputeFilteredDataStatHandler(tornado.web.RequestHandler): def get(self): self.render('test_compute_filtered_data_stat.html') # 14 class TestGetFilteredDataStatHandler(tornado.web.RequestHandler): def get(self): self.render('test_get_filtered_data_stat.html') # 15 class TestComputeBaseStationHourSummaryHandler(tornado.web.RequestHandler): def get(self): self.render('test_compute_base_station_hour_summary.html') # 16 class TestDownloadBaseStationHourSummaryHandler(tornado.web.RequestHandler): def get(self): self.render('test_download_base_station_hour_summary.html') # 17 class TestGetBaseStationHourSummaryHandler(tornado.web.RequestHandler): def get(self): self.render('test_get_base_station_hour_summary.html') # 18 class TestComputeUuidCellHourHandler(tornado.web.RequestHandler): def get(self): self.render('test_compute_uuid_cell_hour.html') # 19 class TestGetUuidCellHourHandler(tornado.web.RequestHandler): def get(self): self.render('test_get_uuid_cell_hour.html') # 20 class TestDeleteAllTablesHandler(tornado.web.RequestHandler): def get(self): self.render('test_delete_all_tables.html') # 30 class TestComputePeopleRoamHandler(tornado.web.RequestHandler): def get(self): self.render('test_compute_peo_roam.html') # 31 class TestComputePeopleTypeHandler(tornado.web.RequestHandler): def get(self): self.render('test_compute_peo_type.html') # 32 class TestComputeODHandler(tornado.web.RequestHandler): def get(self): self.render('test_compute_uuid_od.html') # 33 class TestUploadAreaStationHandler(tornado.web.RequestHandler): def get(self): self.render('test_upload_area_station.html') # 34 class TestComputeBusinessDataHandler(tornado.web.RequestHandler): def get(self): self.render('test_compute_business_data.html') # 35 class TestDownloadBusinessDataHandler(tornado.web.RequestHandler): def get(self): self.render('test_download_business_data.html') class BaseHandler(): def runProcess(self, exe): p = subprocess.Popen(exe, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while(True): retcode = p.poll() #returns None while subprocess is running line = p.stdout.readline() yield line if(retcode is not None): break plog("\nFinish process") def runCmd(self, inner, process_name, target_fuc): cmd = """ %s -e "%s"; """ % (_odps_client, inner) plog("cmd: " + cmd) arguments = shlex.split(cmd) #plog("arguments: " + ' '.join(arguments)) process = multiprocessing.Process(name = process_name, target = target_fuc, args = (arguments,)) process.start() def runSQL(self, sql, process_name, target_fuc): process = multiprocessing.Process(name = process_name, target = target_fuc, args = (sql,)) process.start() def runSQL2(self, sql1, sql2, process_name, target_fuc): process = multiprocessing.Process(name = process_name, target = target_fuc, args = (sql1,sql2,)) process.start() # 1 class CreateCustomerRawDataHandler(tornado.web.RequestHandler, BaseHandler): def isValidType(self, f_type): valid_type = ["bigint", "double", "string", "datetime", "boolean"] if f_type in valid_type: return True else: return False def doCreateCustomerRaw(self, exe): name = multiprocessing.current_process().name plog(name + ": " + "Starting") db_client = MongoClient('localhost', 27017) db = db_client[self.project_id + "_db"] collection = db["task-progress"] result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["create_customer_raw_data_table"]}) result = collection.insert_one( { "project_id" : self.project_id, "task_id" : _task_id["create_customer_raw_data_table"], "progress" : 0, "lastModified" : datetime.datetime.utcnow() } ) for line in BaseHandler.runProcess(self, exe): print line, if "ID" in line: session_id = line.split()[2] plog("session_id: " + session_id) if "OK" in line: result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["create_customer_raw_data_table"]}) result = collection.insert_one( { "project_id" : self.project_id, "task_id" : _task_id["create_customer_raw_data_table"], "aliyun_sess_id" : session_id, "progress" : 100, "lastModified" : datetime.datetime.utcnow() } ) plog("result.inserted_id: " + str(result.inserted_id)) plog(name + ": " + "Exiting") db_client.close() def post(self): fields_raw = self.get_argument('fields') fields = fields_raw.split(",") self.project_id = self.get_argument('project_id'); plog("fields: " + ', '.join(fields)) plog("project_id: " + self.project_id) is_valid = True # 类型是否完全合法 #Eg: create table if not exists nanjing1_customer_raw_data (uuid string, # call_in bigint, call_out bigint, time bigint, cell_id bigint, # cell_name string, lon double, lat double, in_room bigint, # is_roam bigint); fields_list = "" for pairs in fields: (f_name, f_type) = pairs.split("#") plog("f_name: " + f_name + ", " + "f_type: " + f_type) # 检查类型是否合法 if(not self.isValidType(f_type)): is_valid = False if is_valid: return_msg = "Create table successful" else: return_msg = "Type error, please check" #self.render('create_customer_raw_data_result.html', # return_msg = return_msg) obj = {'return_msg' : return_msg} self.write(json_encode(obj)) return fields_list = fields_raw.replace("#", " ") sql = "drop table if exists " + self.project_id + "_customer_raw_data; " + \ "create table if not exists " + self.project_id + \ "_customer_raw_data (" + fields_list + ")" BaseHandler.runCmd(self, sql, \ "create_customer_raw_data_process", self.doCreateCustomerRaw) # 将客户原始有效字段存储到元数据中 db_client = MongoClient('localhost', 27017) db = db_client[self.project_id + "_db"] collection = db["customer_fields"] result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["create_customer_raw_data_table"]}) result = collection.insert_one( { "project_id" : self.project_id, "task_id" : _task_id["create_customer_raw_data_table"], "fields_raw" : fields_raw, "lastModified" : datetime.datetime.utcnow() } ) db_client.close() #self.render('create_customer_raw_data_result.html', # return_msg = return_msg) obj = {'return_msg' : return_msg} self.write(json_encode(obj)) # 2 class UploadHandler(tornado.web.RequestHandler, BaseHandler): def getTimeFieldType(self, raw_fields): for pairs in raw_fields.split(","): (f_name, f_type) = pairs.split("#") if(f_name == "time"): return f_type def doUpload(self, exe): name = multiprocessing.current_process().name plog(name+" "+"Starting") total = 0 finished = 0 progress = 0 session_id = "" db_client = MongoClient('localhost', 27017) db = db_client[self.project_id + "_db"] collection = db["task-progress"] result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["upload_customer_raw_data"]}) result = collection.insert_one( { "project_id" : self.project_id, "task_id" : _task_id["upload_customer_raw_data"], "progress" : 0, "lastModified" : datetime.datetime.utcnow() } ) for line in BaseHandler.runProcess(self, exe): print line, # extract upload progess and total block if "Upload session" in line: session_id = line.split()[2] plog("session_id: " + session_id) result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["upload_customer_raw_data"]}) result = collection.insert_one( { "project_id" : self.project_id, "task_id" : _task_id["upload_customer_raw_data"], "aliyun_sess_id" : session_id, "progress" : progress, "lastModified" : datetime.datetime.utcnow() } ) plog("result.inserted_id: " + str(result.inserted_id)) if "Split input to" in line: total = int(line.split()[5]) plog("total: " + str(total)) elif "upload block complete" in line: finished += 1 plog("finished: " + str(finished)) progress = int((1.0 * finished / total) * 100) plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["upload_customer_raw_data"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) plog("result.matched_count: "+str(result.matched_count)) plog("result.modified_count: "+str(result.modified_count)) plog(name+" Exiting") db_client.close() def post(self): # 解析输入的参数 self.project_id = self.get_argument('project_id') data_path = self.get_argument('data_path') #aliyun_table = self.get_argument('aliyun_table') aliyun_table = self.project_id + "_customer_raw_data" threads_num = self.get_argument('threads_num') row_delimiter = self.get_argument('row_delimiter') col_delimiter = self.get_argument('col_delimiter') plog("aliyun_table: " + aliyun_table) plog("threads_num: " + threads_num) plog("row_delimiter: " + row_delimiter) plog("col_delimiter: " + col_delimiter) # 获取字段类型 db_client = MongoClient('localhost', 27017) db = db_client[self.project_id + "_db"] collection = db["customer_fields"] task_id = _task_id["create_customer_raw_data_table"] cursor = collection.find({"project_id": self.project_id, "task_id": task_id}) if(cursor.count() == 1): fields_raw = cursor.next()["fields_raw"] plog("fields_raw: " + fields_raw) timeFieldType = self.getTimeFieldType(fields_raw) if(timeFieldType=="bigint"): # 构造阿里云上运行的sql upload_cmd = "truncate table " + aliyun_table + ";" + \ "tunnel upload " + data_path + " " + aliyun_table +\ " -bs 10 -threads " + threads_num + " -s true" +\ " -dbr true -mbr 999999999" # 调用阿里云执行sql BaseHandler.runCmd(self, upload_cmd, "upload_process", self.doUpload) elif(timeFieldType=="datetime"): # Time format: 2015-06-21 04:01:00 # 构造阿里云上运行的sql upload_cmd = "truncate table " + aliyun_table + ";" +\ "tunnel upload " + data_path + " " + aliyun_table +\ " -bs 10 -threads " + threads_num + " -s true" +\ " -dbr true -mbr 999999999 -dfp 'yyyy-MM-dd HH:mm:ss'" # 调用阿里云执行sql BaseHandler.runCmd(self, upload_cmd, "upload_process", self.doUpload) else: plog("Warning: project_id: " + self.project_id + ", task_id: " + task_id + " time field format not support now.") #self.render('upload_result.html', # project_id = self.project_id, # data_path = data_path, # aliyun_table = aliyun_table, # threads_num = threads_num, # row_delimiter = row_delimiter, # col_delimiter = col_delimiter, # ret_msg = "Time field format not support") obj = {'project_id' : project_id, 'data_path' : data_path, 'aliyun_table' : aliyun_table, 'threads_num' : threads_num, 'row_delimiter' : row_delimiter, 'col_delimiter' : col_delimiter, 'ret_msg' : "Time field format not support"} self.write(json_encode(obj)) return else: plog("Warning: project_id: " + self.project_id + ", task_id: " + task_id + " has more than one progess record") #self.render('upload_result.html', # project_id = self.project_id, # data_path = data_path, # aliyun_table = aliyun_table, # threads_num = threads_num, # row_delimiter = row_delimiter, # col_delimiter = col_delimiter, # ret_msg = "Error") obj = {'project_id' : project_id, 'data_path' : data_path, 'aliyun_table' : aliyun_table, 'threads_num' : threads_num, 'row_delimiter' : row_delimiter, 'col_delimiter' : col_delimiter, 'ret_msg' : "Error"} self.write(json_encode(obj)) return db_client.close() # 渲染结果页面 #self.render('upload_result.html', # project_id = self.project_id, # data_path = data_path, # aliyun_table = aliyun_table, # threads_num = threads_num, # row_delimiter = row_delimiter, # col_delimiter = col_delimiter, # ret_msg = "Success") obj = {'project_id' : self.project_id, 'data_path' : data_path, 'aliyun_table' : aliyun_table, 'threads_num' : threads_num, 'row_delimiter' : row_delimiter, 'col_delimiter' : col_delimiter, 'ret_msg' : "Success"} self.write(json_encode(obj)) # 3 class RequestTaskProgressHandler(tornado.web.RequestHandler): def post(self): project_id = self.get_argument('project_id') task_id = self.get_argument('task_id') plog("project_id: " + project_id) plog("task_id: " + task_id) progress = -1 db_client = MongoClient('localhost', 27017) db = db_client[project_id + "_db"] collection = db["task-progress"] cursor = collection.find({"project_id": project_id, "task_id": int(task_id)}) plog("cursor.count(): " + str(cursor.count())) if(cursor.count() == 1): progress = cursor.next()["progress"] else: plog("Warning: project_id: " + project_id + ", task_id: " + task_id + " has more than one progess record") progress = 0 #self.render('request_task_progress_result.html', # project_id = project_id, # task_id = task_id, # progress = progress, # ret_msg = "Error") obj = {'project_id' : project_id, 'task_id' : task_id, 'progress' : progress, 'ret_msg' : "Error"} self.write(json_encode(obj)) return db_client.close() #self.render('request_task_progress_result.html', # project_id = project_id, # task_id = task_id, # progress = progress, # ret_msg = "Success") obj = {'project_id' : project_id, 'task_id' : task_id, 'progress' : progress, 'ret_msg' : "Success"} self.write(json_encode(obj)) # 4 class TransformToInnerFormatHandler(tornado.web.RequestHandler, BaseHandler): def extractValidFields(self, raw_fields): fields = [] types = [] valid_field = ["uuid", "time", "lon", "lat", "cell_id", "cell_name", "is_roam", "in_room", "call_in", "call_out"] for pairs in raw_fields.split(","): (f_name, f_type) = pairs.split("#") if(f_name in valid_field): fields.append(f_name) types.append(f_type) else: continue return (fields, types) def getTimeFieldType(self, raw_fields): for pairs in raw_fields.split(","): (f_name, f_type) = pairs.split("#") if(f_name == "time"): return f_type def doTransformToInnerFormat(self, exe): name = multiprocessing.current_process().name plog(name + " " + "Starting") progress = 0 session_id = "" db_client = MongoClient('localhost', 27017) db = db_client[self.project_id + "_db"] collection = db["task-progress"] count = 0; result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["transform_to_spatio_temporal_raw_data"]}) result = collection.insert_one( { "project_id" : self.project_id, "task_id" : _task_id["transform_to_spatio_temporal_raw_data"], "progress" : 0, "lastModified" : datetime.datetime.utcnow() } ) for line in BaseHandler.runProcess(self, exe): print line, if "ID" in line: session_id = line.split()[2] plog("session_id: " + session_id) result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["transform_to_spatio_temporal_raw_data"]}) result = collection.insert_one( { "project_id" : self.project_id, "task_id" : _task_id["transform_to_spatio_temporal_raw_data"], "aliyun_sess_id" : session_id, "progress" : progress, "lastModified" : datetime.datetime.utcnow() } ) plog("result.inserted_id: " + str(result.inserted_id)) elif "OK" in line: progress = 100 plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["transform_to_spatio_temporal_raw_data"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) plog("result.matched_count: "+str(result.matched_count)) plog("result.modified_count: "+str(result.modified_count)) elif "%" in line: count += 1 l = line.rfind("[") r = line.rfind("%") progress = int(line[l+1:r]) # Not good look, use bellow progress = int((1.0 * count / (count + 1)) * 100) plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["transform_to_spatio_temporal_raw_data"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) plog("result.matched_count: "+str(result.matched_count)) plog("result.modified_count: "+str(result.modified_count)) db_client.close() plog(name+" Exiting") def post(self): self.project_id = self.get_argument('project_id'); plog("project_id: " + self.project_id) db_client = MongoClient('localhost', 27017) db = db_client[self.project_id + "_db"] collection = db["customer_fields"] task_id = _task_id["create_customer_raw_data_table"] cursor = collection.find({"project_id": self.project_id, "task_id": task_id}) if(cursor.count() == 1): fields_raw = cursor.next()["fields_raw"] plog("fields_raw: " + fields_raw) (fields, types) = self.extractValidFields(fields_raw) timeFieldType = self.getTimeFieldType(fields_raw) # 合成需要取出的字段 sql = "" if("uuid" in fields and "lon" in fields and "lat" in fields and "time" in fields): if(timeFieldType == "bigint"): sql = "create table if not exists " + self.project_id + \ "_spatio_temporal_raw_data(uuid string, lon double, lat double, " + \ "time bigint) partitioned by (date_p string); " + \ "insert overwrite table " + self.project_id + \ "_spatio_temporal_raw_data partition(date_p) select " + \ "uuid, lon, lat, time" +\ ", to_char(from_unixtime(time), 'yyyymmdd') as date_p "+\ "from " + self.project_id + "_customer_raw_data " + \ "where lat is not null and lon is not null and uuid is not null "+\ "and time is not null and lat>0 and lon>0 and time>0 group by "+\ "uuid, time, lat, lon;" elif(timeFieldType == "datetime"): # Time format: 2015-06-21 04:01:00 field_list = "uuid, lon, lat, unix_timestamp(time)" sql = "create table if not exists " + self.project_id + \ "_spatio_temporal_raw_data(uuid string, lon double, lat double, " + \ "time bigint) partitioned by (date_p string); " + \ "insert overwrite table " + self.project_id + \ "_spatio_temporal_raw_data partition(date_p) select " + \ "uuid, lon, lat, unix_timestamp(time)" +\ ", to_char(time, 'yyyymmdd') as date_p "+\ "from " + self.project_id + "_customer_raw_data " + \ "where lat is not null and lon is not null and uuid is not null "+\ "and time is not null and lat>0 and lon>0 and "+\ "unix_timestamp(time)>0 group by "+\ "uuid, time, lat, lon;" else: plog("Warning: project_id: " + self.project_id + ", task_id: " + task_id + " time format not supported") progress = 0 #self.render('transform_to_inner_format_result.html', # project_id = self.project_id, # task_id = task_id, # ret_msg = "Time format not supported") obj = {'project_id' : project_id, 'task_id' : task_id, 'ret_msg' : "Time format not supported"} self.write(json_encode(obj)) return plog("sql: " + sql) BaseHandler.runCmd(self, sql, \ "transform_to_inner_format_process", self.doTransformToInnerFormat) else: plog("Warning: project_id: " + self.project_id + ", task_id: " + task_id + " has more than one progess record") progress = 0 #self.render('transform_to_inner_format_result.html', # project_id = self.project_id, # task_id = task_id, # ret_msg = "Error") obj = {'project_id' : project_id, 'task_id' : task_id, 'ret_msg' : "Error"} self.write(json_encode(obj)) return db_client.close() #self.render('transform_to_inner_format_result.html', # project_id = self.project_id, # task_id = task_id, # fields_raw = fields_raw, # ret_msg = "Success") obj = {'project_id' : self.project_id, 'task_id' : task_id, 'ret_msg' : "Success"} self.write(json_encode(obj)) # 5 class ComputeRawDataStatHandler(tornado.web.RequestHandler, BaseHandler): def processResult(self, raw): result = raw.split("\n")[1:-1] new_result = [] for pair in result: date_p = pair.split(",")[0][1:-1] count = pair.split(",")[1] new_result.append("" + str(date_p) + "," + count) result_str = '#'.join(new_result) plog("Raw stat: " + str(result_str)) return result_str def doComputeRawDataStat(self, sql): name = multiprocessing.current_process().name plog(name + " " + "Starting") progress = 0 # 建立数据库连接 db_client = MongoClient('localhost', 27017) db = db_client[self.project_id + "_db"] collection = db["task-progress"] count = 0; result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["compute_raw_data_stat"]}) result = collection.insert_one( { "project_id" : self.project_id, "task_id" : _task_id["compute_raw_data_stat"], "progress" : progress, "lastModified" : datetime.datetime.utcnow() } ) plog("result.inserted_id: " + str(result.inserted_id)) instance = odps.run_sql(sql) while(not instance.is_successful()): count += 1 progress = int((1.0 * count / (count + 1)) * 100) plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["compute_raw_data_stat"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) time.sleep(5) raw_result = instance.get_task_result(instance.get_task_names()[0]) plog("raw_result: " + raw_result) collection2 = db["local-result"] raw_stat = self.processResult(raw_result) result = collection2.delete_many({ "project_id": self.project_id, "task_id": _task_id["compute_raw_data_stat"]}) result = collection2.insert_one( { "project_id" : self.project_id, "task_id" : _task_id["compute_raw_data_stat"], "result" : raw_stat, "lastModified" : datetime.datetime.utcnow() } ) progress = 100 plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["compute_raw_data_stat"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) db_client.close() plog("result.matched_count: "+str(result.matched_count)) plog("result.modified_count: "+str(result.modified_count)) def post(self): # 解析输入的参数 self.project_id = self.get_argument('project_id'); # 构造阿里云上运行的sql # day #sql = ('select date_p, count(*) as count from ' # '' + self.project_id + '_spatio_temporal_raw_data ' # 'group by date_p order by date_p limit 100') # hour sql = ('select to_char(from_unixtime(time), "yyyyMMddHH") as hour, ' 'count(*) as count from ' '' + self.project_id + '_spatio_temporal_raw_data ' 'group by to_char(from_unixtime(time), "yyyyMMddHH") ' 'order by hour limit 2400') plog("sql: " + sql) # 调用阿里云执行sql BaseHandler.runSQL(self, sql, \ "compute_raw_data_stat", self.doComputeRawDataStat) # 渲染结果页面 #self.render('compute_raw_data_stat_result.html', # project_id = self.project_id, # ret_msg = "Success") obj = {'project_id' : self.project_id, 'ret_msg' : "Success"} self.write(json_encode(obj)) # 6 class GetRawDataStatHandler(tornado.web.RequestHandler, BaseHandler): def post(self): # 解析输入的参数 project_id = self.get_argument('project_id'); result = "" # 查询本地数据库 db_client = MongoClient('localhost', 27017) db = db_client[project_id + "_db"] collection = db["local-result"] cursor = collection.find({"project_id": project_id, "task_id": _task_id["compute_raw_data_stat"]}) plog("cursor.count(): " + str(cursor.count())) if(cursor.count() == 1): raw_stat = cursor.next()["result"] else: plog("Warning: project_id: " + project_id + ", task_id: " + str(_task_id["compute_raw_data_stat"]) + " has more than one progess record") raw_stat = "" #self.render('get_raw_data_stat_result.html', # project_id = project_id, # result = raw_stat, # ret_msg = "Error") obj = {'project_id' : project_id, 'result' : raw_stat, 'ret_msg' : "Error"} self.write(json_encode(obj)) return db_client.close() plog("Get raw stat: " + str(raw_stat)) # 渲染结果页面 #self.render('get_raw_data_stat_result.html', # project_id = project_id, # result = raw_stat, # ret_msg = "Success") obj = {'project_id' : project_id, 'result' : raw_stat, 'ret_msg' : "Success"} self.write(json_encode(obj)) # 7 class ComputePeopleDistributionHandler(tornado.web.RequestHandler, BaseHandler): def processResult(self, raw): result = raw.split("\n")[1:-1] result_str = '#'.join(result) plog("People distribution: " + str(result_str)) return result_str def doComputePeopleDistribution(self, sql): # 调用后台阿里云后, 这里处理其返回结果 name = multiprocessing.current_process().name plog(name + " " + "Starting") progress = 0 # 建立数据库连接 db_client = MongoClient('localhost', 27017) db = db_client[self.project_id + "_db"] collection = db["task-progress"] count = 0; result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["compute_people_distribution"]}) result = collection.insert_one( { "project_id" : self.project_id, "task_id" : _task_id["compute_people_distribution"], "progress" : progress, "lastModified" : datetime.datetime.utcnow() } ) plog("result.inserted_id: " + str(result.inserted_id)) instance = odps.run_sql(sql) while(not instance.is_successful()): #plog("is_successful(): " + str(instance.is_successful())) #plog("is_terminated(): " + str(instance.is_terminated())) count += 1 progress = int((1.0 * count / (count + 1)) * 100) plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["compute_people_distribution"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) time.sleep(5) #plog(instance.get_task_result(instance.get_task_names()[0])) raw_result = instance.get_task_result(instance.get_task_names()[0]) # 把人基于数据量的分布写入本地数据库 collection2 = db["local-result"] people_distribution = self.processResult(raw_result) result = collection2.update_one( {"project_id" : self.project_id, "task_id" : _task_id["compute_people_distribution"] }, { "$set" : { "result" : people_distribution }, "$currentDate": {"lstModified": True} } ) progress = 100 plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["compute_people_distribution"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) db_client.close() plog("result.matched_count: "+str(result.matched_count)) plog("result.modified_count: "+str(result.modified_count)) def post(self): # 解析输入的参数 self.project_id = self.get_argument('project_id'); self.interval_size = self.get_argument('interval_size'); self.date_p = self.get_argument('date_p'); self.top_n = self.get_argument('top_n'); # 构造阿里云上运行的sql sql = ('select t.r as interval, count(*) as count from (' 'select uuid, floor((count(*)/' + self.interval_size + ')) as r ' 'from ' + self.project_id + '_spatio_temporal_raw_data ' 'where date_p=' + self.date_p + ' ' 'group by uuid) t ' 'group by t.r ' 'order by interval ' 'limit ' + self.top_n + ';') plog("sql: " + sql) # 调用阿里云执行sql BaseHandler.runSQL(self, sql, \ "compute_people_distribution", self.doComputePeopleDistribution) db_client = MongoClient('localhost', 27017) db = db_client[self.project_id + "_db"] collection2 = db["local-result"] result = collection2.delete_many({ "project_id": self.project_id, "task_id": _task_id["compute_people_distribution"]}) result = collection2.insert_one( { "project_id" : self.project_id, "task_id" : _task_id["compute_people_distribution"], "interval_size" : self.interval_size, "top_n" : self.top_n, "result" : "Not Computed", "lastModified" : datetime.datetime.utcnow() } ) db_client.close() # 渲染结果页面 #self.render('compute_people_distribution_result.html', # project_id = self.project_id, # interval_size = self.interval_size, # date_p = self.date_p, # top_n = self.top_n, # ret_msg = "Success") obj = {'project_id' : self.project_id, 'interval_size' : self.interval_size, 'date_p' : self.date_p, 'top_n' : self.top_n, 'ret_msg' : "Success"} self.write(json_encode(obj)) # 8 class GetPeopleDistributionHandler(tornado.web.RequestHandler, BaseHandler): def post(self): # 解析输入的参数 project_id = self.get_argument('project_id'); # 查询本地数据库 db_client = MongoClient('localhost', 27017) db = db_client[project_id + "_db"] collection = db["local-result"] cursor = collection.find({"project_id": project_id, "task_id": _task_id["compute_people_distribution"]}) plog("cursor.count(): " + str(cursor.count())) people_distribution = "" interval_size = "" top_n = "" if(cursor.count() == 1): res = cursor.next() people_distribution = res["result"] interval_size = res["interval_size"] top_n = res["top_n"] else: plog("Warning: project_id: " + project_id + ", task_id: " + str(_task_id["compute_people_distribution"]) + " has more than one progess record") people_distribution = "" #self.render('get_people_distribution_result.html', # project_id = project_id, # people_distribution = people_distribution, # interval_size = interval_size, # top_n = top_n, # ret_msg = "Error") obj = {'project_id' : project_id, 'people_distribution' : people_distribution, 'interval_size' : interval_size, 'top_n' : top_n, 'ret_msg' : "Error"} self.write(json_encode(obj)) return db_client.close() plog("Get people_distribution: " + str(people_distribution)) # 渲染结果页面 #self.render('get_people_distribution_result.html', # project_id = project_id, # people_distribution = people_distribution, # interval_size = interval_size, # top_n = top_n, # ret_msg = "Success") obj = {'project_id' : project_id, 'people_distribution' : people_distribution, 'interval_size' : interval_size, 'top_n' : top_n, 'ret_msg' : "Success"} self.write(json_encode(obj)) # 9 class ComputeBaseStationInfoHandler(tornado.web.RequestHandler, BaseHandler): def doComputeBaseStationInfo(self, sql1, sql2): name = multiprocessing.current_process().name plog(name + " " + "Starting") progress = 0 # 建立数据库连接 db_client = MongoClient('localhost', 27017) db = db_client[self.project_id + "_db"] collection = db["task-progress"] count = 0; result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["compute_base_station_info"]}) result = collection.insert_one( { "project_id" : self.project_id, "task_id" : _task_id["compute_base_station_info"], "progress" : progress, "lastModified" : datetime.datetime.utcnow() } ) plog("result.inserted_id: " + str(result.inserted_id)) instance1 = odps.run_sql(sql1) while(not instance1.is_successful()): time.sleep(1) plog("sql1 runs Successful") instance2 = odps.run_sql(sql2) while(not instance2.is_successful()): count += 1 progress = int((1.0 * count / (count + 1)) * 100) plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["compute_base_station_info"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) time.sleep(5) progress = 100 plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["compute_base_station_info"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) db_client.close() plog("result.matched_count: "+str(result.matched_count)) plog("result.modified_count: "+str(result.modified_count)) def post(self): # 解析输入的参数 self.project_id = self.get_argument('project_id'); # 构造阿里云上运行的sql sql1 = ('create table if not exists ' '' + self.project_id + '_base_station_info' '(id bigint, lon double, lat double)') sql2 = ('insert overwrite table ' '' + self.project_id + '_base_station_info ' 'select row_number() over(partition by A.tmp order by A.tmp) as id,' 'A.lon, A.lat ' 'from (select distinct lon, lat, 1 as tmp ' 'from ' + self.project_id + '_spatio_temporal_raw_data) A;') plog("sql1: " + sql1) plog("sql2: " + sql2) # 调用阿里云执行sql BaseHandler.runSQL2(self, sql1, sql2, \ "compute_raw_data_stat", self.doComputeBaseStationInfo) # 渲染结果页面 #self.render('compute_base_station_info_result.html', # project_id = self.project_id, # ret_msg = "Success") obj = {'project_id' : self.project_id, 'ret_msg' : "Success"} self.write(json_encode(obj)) # 10 class DownloadBaseStationInfoHandler(tornado.web.RequestHandler, BaseHandler): def doDownloadBaseStationInfo(self, exe): name = multiprocessing.current_process().name plog(name + " " + "Starting") progress = 0 count = 0 db_client = MongoClient('localhost', 27017) db = db_client[self.project_id + "_db"] collection = db["task-progress"] result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["download_base_station_info"]}) result = collection.insert_one( { "project_id" : self.project_id, "task_id" : _task_id["download_base_station_info"], "progress" : progress, "lastModified" : datetime.datetime.utcnow() } ) for line in BaseHandler.runProcess(self, exe): print line, # extract upload progess and total block if "file" in line: count += 1 progress = int((1.0 * count / (count + 1)) * 100) plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["download_base_station_info"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) plog("result.matched_count: "+str(result.matched_count)) plog("result.modified_count: "+str(result.modified_count)) elif "download OK" in line: progress = 100 plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["download_base_station_info"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) plog("result.matched_count: "+str(result.matched_count)) plog("result.modified_count: "+str(result.modified_count)) plog(name+" Exiting") db_client.close() def post(self): # 解析输入的参数 self.project_id = self.get_argument('project_id'); download_cmd = ('tunnel download ' + self.project_id + '_base_station_info ' + _download_folder + '/' '' + self.project_id + '_base_station_info.csv ' '-h true;') plog("download_cmd: " + download_cmd) # 调用阿里云执行 BaseHandler.runCmd(self, download_cmd, \ "download_base_station_info", \ self.doDownloadBaseStationInfo) # 渲染结果页面 #self.render('compute_base_station_info_result.html', # project_id = self.project_id, # ret_msg = "Success") obj = {'project_id' : self.project_id, 'ret_msg' : "Success"} self.write(json_encode(obj)) # 11 class GetBaseStationInfoHandler(tornado.web.RequestHandler, BaseHandler): def post(self): # 解析输入的参数 project_id = self.get_argument('project_id'); # 渲染结果页面 #self.render('get_raw_data_stat_result.html', # project_id = project_id, # result = _download_folder, # ret_msg = "Success") obj = {'project_id' : project_id, 'download_folder' : _download_folder, 'ret_msg' : "Success"} self.write(json_encode(obj)) # 12 class FilterDataWithRangeHandler(tornado.web.RequestHandler, BaseHandler): def doFilterDataWithRange(self, sql1, sql2): plog("sql1: " + sql1) plog("sql2: " + sql2) name = multiprocessing.current_process().name plog(name + " " + "Starting") progress = 0 # 建立数据库连接 db_client = MongoClient('localhost', 27017) db = db_client[self.project_id + "_db"] collection = db["task-progress"] count = 0; result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["filter_data_with_range"]}) result = collection.insert_one( { "project_id" : self.project_id, "task_id" : _task_id["filter_data_with_range"], "progress" : progress, "lastModified" : datetime.datetime.utcnow() } ) plog("result.inserted_id: " + str(result.inserted_id)) instance1 = odps.run_sql(sql1) while(not instance1.is_successful()): time.sleep(1) plog("sql1 runs Successful") instance2 = odps.run_sql(sql2) while(not instance2.is_successful()): count += 1 progress = int((1.0 * count / (count + 1)) * 100) plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["filter_data_with_range"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) time.sleep(5) progress = 100 plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["filter_data_with_range"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) db_client.close() plog("result.matched_count: "+str(result.matched_count)) plog("result.modified_count: "+str(result.modified_count)) def post(self): # 解析输入的参数 self.project_id = self.get_argument('project_id'); self.count_min = self.get_argument('count_min'); self.count_max = self.get_argument('count_max'); # 构造阿里云上运行的sql sql1 = ('create table if not exists ' '' + self.project_id + '_filtered_raw_data ' '(uuid string, lon double, lat double, bs_id bigint, ' 'time bigint, count bigint) ' 'partitioned by (date_p string);') sql2 = ('insert overwrite table ' + self.project_id + '_filtered_raw_data ' 'partition(date_p) ' 'select D.uuid, D.lon, D.lat, E.id as bs_id, D.time, ' 'D.count, D.date_p from ' '(select A.uuid, A.lon, A.lat, A.time, B.count, A.date_p ' ' from ' + self.project_id + '_spatio_temporal_raw_data A ' 'inner join ' '(select C.uuid, C.date_p, C.count from ' '(select date_p, uuid, count(*) as count from ' '' + self.project_id + '_spatio_temporal_raw_data ' 'group by uuid, date_p) C ' 'where C.count>' + self.count_min + '' ' and C.count<' + self.count_max + ') B ' 'on A.uuid=B.uuid and A.date_p=B.date_p) D left outer join ' '' + self.project_id + '_base_station_info E ' 'on D.lon=E.lon and D.lat=E.lat;') plog("sql1: " + sql1) plog("sql2: " + sql2) # 调用阿里云执行sql BaseHandler.runSQL2(self, sql1, sql2, \ "filter_data_with_range", self.doFilterDataWithRange) db_client = MongoClient('localhost', 27017) db = db_client[self.project_id + "_db"] collection2 = db["local-result"] result = collection2.delete_many({ "project_id": self.project_id, "task_id": _task_id["filter_data_with_range"]}) result = collection2.insert_one( { "project_id" : self.project_id, "task_id" : _task_id["filter_data_with_range"], "count_min" : self.count_min, "count_max" : self.count_max, "result" : "None", "lastModified" : datetime.datetime.utcnow() } ) db_client.close() # 渲染结果页面 #self.render('filter_data_with_range_result.html', # project_id = self.project_id, # count_min = self.count_min, # count_max = self.count_max, # ret_msg = "Success") obj = {'project_id' : self.project_id, 'count_min' : self.count_min, 'count_max' : self.count_max, 'ret_msg' : "Success"} self.write(json_encode(obj)) # 13 class ComputeFilteredDataStatHandler(tornado.web.RequestHandler, BaseHandler): def processResult(self, raw): result = raw.split("\n")[1:-1] new_result = [] for pair in result: date_p = pair.split(",")[0][1:-1] count = pair.split(",")[1] new_result.append("" + str(date_p) + "," + count) result_str = '#'.join(new_result) plog("Raw stat: " + str(result_str)) return result_str def doComputeFilteredDataStat(self, sql): name = multiprocessing.current_process().name plog(name + " " + "Starting") progress = 0 # 建立数据库连接 db_client = MongoClient('localhost', 27017) db = db_client[self.project_id + "_db"] collection = db["task-progress"] count = 0; result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["compute_filtered_data_stat"]}) result = collection.insert_one( { "project_id" : self.project_id, "task_id" : _task_id["compute_filtered_data_stat"], "progress" : progress, "lastModified" : datetime.datetime.utcnow() } ) plog("result.inserted_id: " + str(result.inserted_id)) instance = odps.run_sql(sql) while(not instance.is_successful()): count += 1 progress = int((1.0 * count / (count + 1)) * 100) plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["compute_filtered_data_stat"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) time.sleep(5) raw_result = instance.get_task_result(instance.get_task_names()[0]) collection2 = db["local-result"] filtered_stat = self.processResult(raw_result) result = collection2.update_one( {"project_id" : self.project_id, "task_id" : _task_id["filter_data_with_range"] }, { "$set": { "result": filtered_stat }, "$currentDate": {"lastModified": True} } ) progress = 100 plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["compute_filtered_data_stat"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) db_client.close() plog("result.matched_count: "+str(result.matched_count)) plog("result.modified_count: "+str(result.modified_count)) def post(self): # 解析输入的参数 self.project_id = self.get_argument('project_id'); # 构造阿里云上运行的sql sql = ('select date_p, count(*) as count from ' '' + self.project_id + '_filtered_raw_data ' 'group by date_p order by date_p limit 100') plog("sql: " + sql) # 调用阿里云执行sql BaseHandler.runSQL(self, sql, \ "compute_filtered_data_stat", self.doComputeFilteredDataStat) # 渲染结果页面 #self.render('compute_filtered_data_stat_result.html', # project_id = self.project_id, # ret_msg = "Success") obj = {'project_id' : self.project_id, 'ret_msg' : "Success"} self.write(json_encode(obj)) # 14 class GetFilteredDataStatHandler(tornado.web.RequestHandler, BaseHandler): def post(self): # 解析输入的参数 project_id = self.get_argument('project_id'); filtered_stat = "" # 查询本地数据库 db_client = MongoClient('localhost', 27017) db = db_client[project_id + "_db"] collection = db["local-result"] cursor = collection.find({"project_id": project_id, "task_id": _task_id["filter_data_with_range"]}) plog("cursor.count(): " + str(cursor.count())) if(cursor.count() == 1): filtered_stat = cursor.next()["result"] else: plog("Warning: project_id: " + project_id + ", task_id: " + str(_task_id["filter_data_with_range"]) + " has more than one progess record") filtered_stat = "" #self.render('get_filtered_data_stat_result.html', # project_id = project_id, # result = filtered_stat, # ret_msg = "Error") obj = {'project_id' : project_id, 'filtered_stat' : filtered_stat, 'ret_msg' : "Error"} self.write(json_encode(obj)) return db_client.close() # 渲染结果页面 #self.render('get_filtered_data_stat_result.html', # project_id = project_id, # result = filtered_stat, # ret_msg = "Success") obj = {'project_id' : project_id, 'filtered_stat' : filtered_stat, 'ret_msg' : "Success"} self.write(json_encode(obj)) # 15 class ComputeBaseStationHourSummaryHandler(tornado.web.RequestHandler, BaseHandler): def doComputeBaseStationHourSummary(self, sql1, sql2): name = multiprocessing.current_process().name plog(name + " " + "Starting") progress = 0 # 建立数据库连接 db_client = MongoClient('localhost', 27017) db = db_client[self.project_id + "_db"] collection = db["task-progress"] count = 0; result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["compute_base_station_hour_summary"]}) result = collection.insert_one( { "project_id" : self.project_id, "task_id" : _task_id["compute_base_station_hour_summary"], "progress" : progress, "lastModified" : datetime.datetime.utcnow() } ) plog("result.inserted_id: " + str(result.inserted_id)) instance1 = odps.run_sql(sql1) while(not instance1.is_successful()): time.sleep(1) plog("sql1 runs Successful") instance2 = odps.run_sql(sql2) while(not instance2.is_successful()): count += 1 progress = int((1.0 * count / (count + 1)) * 100) plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["compute_base_station_hour_summary"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) time.sleep(5) db_client.close() progress = 100 plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["compute_base_station_hour_summary"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) plog("result.matched_count: "+str(result.matched_count)) plog("result.modified_count: "+str(result.modified_count)) def post(self): # 解析输入的参数 self.project_id = self.get_argument('project_id'); # 构造阿里云上运行的sql sql1 = ('create table if not exists ' '' + self.project_id + '_base_station_hour_summary ' '(lon double, lat double, bs_id bigint, time string, count bigint);') sql2 = ('insert overwrite table ' '' + self.project_id + '_base_station_hour_summary ' 'select lon, lat, bs_id, ' 'CONCAT(substr(from_unixtime(time),1,14),\'00:00\') as time,' 'count(*) as count ' 'from ' + self.project_id + '_filtered_raw_data ' 'group by lon, lat, bs_id, substr(from_unixtime(time),1,14);') plog("sql1: " + sql1) plog("sql2: " + sql2) # 调用阿里云执行sql BaseHandler.runSQL2(self, sql1, sql2, \ "compute_base_station_hour_summary", \ self.doComputeBaseStationHourSummary) # 渲染结果页面 #self.render('compute_base_station_hour_summary_result.html', # project_id = self.project_id, # ret_msg = "Success") obj = {'project_id' : self.project_id, 'ret_msg' : "Success"} self.write(json_encode(obj)) # 16 class DownloadBaseStationHourSummaryHandler(tornado.web.RequestHandler, BaseHandler): def doDownloadBaseStationHourSummary(self, exe): name = multiprocessing.current_process().name plog(name + " " + "Starting") progress = 0 count = 0 db_client = MongoClient('localhost', 27017) db = db_client[self.project_id + "_db"] collection = db["task-progress"] result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["download_base_station_hour_summary"]}) result = collection.insert_one( { "project_id" : self.project_id, "task_id" : _task_id["download_base_station_hour_summary"], "progress" : progress, "lastModified" : datetime.datetime.utcnow() } ) for line in BaseHandler.runProcess(self, exe): print line, # extract upload progess and total block if "file" in line: count += 1 progress = int((1.0 * count / (count + 1)) * 100) plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["download_base_station_hour_summary"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) plog("result.matched_count: "+str(result.matched_count)) plog("result.modified_count: "+str(result.modified_count)) elif "download OK" in line: progress = 100 plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["download_base_station_hour_summary"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) plog("result.matched_count: "+str(result.matched_count)) plog("result.modified_count: "+str(result.modified_count)) plog(name+" Exiting") db_client.close() def post(self): # 解析输入的参数 self.project_id = self.get_argument('project_id'); # 构造阿里云上运行的cmd download_cmd = ('tunnel download ' + self.project_id + '_base_station_hour_summary ' + _download_folder + '/' '' + self.project_id + '_base_station_hour_summary.csv ' '-h true;') plog("download_cmd: " + download_cmd) # 调用阿里云执行 BaseHandler.runCmd(self, download_cmd, \ "download_base_station_hour_summary", \ self.doDownloadBaseStationHourSummary) # 渲染结果页面 #self.render('download_base_station_hour_summary_result.html', # project_id = self.project_id, # ret_msg = "Success") obj = {'project_id' : self.project_id, 'ret_msg' : "Success"} self.write(json_encode(obj)) # 17 class GetBaseStationHourSummaryHandler(tornado.web.RequestHandler, BaseHandler): def post(self): # 解析输入的参数 project_id = self.get_argument('project_id'); # 渲染结果页面 #self.render('get_base_station_hour_summary_result.html', # project_id = project_id, # result = _download_folder, # ret_msg = "Success") obj = {'project_id' : project_id, 'download_folder' : _download_folder, 'ret_msg' : "Success"} self.write(json_encode(obj)) # 18 class ComputeUuidCellHourHandler(tornado.web.RequestHandler, BaseHandler): def doComputeUuidCellHour(self, sql1, sql2): name = multiprocessing.current_process().name plog(name + " " + "Starting") progress = 0 # 建立数据库连接 db_client = MongoClient('localhost', 27017) db = db_client[self.project_id + "_db"] collection = db["task-progress"] count = 0; result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["compute_uuid_cell_hour"]}) result = collection.insert_one( { "project_id" : self.project_id, "task_id" : _task_id["compute_uuid_cell_hour"], "progress" : progress, "lastModified" : datetime.datetime.utcnow() } ) plog("result.inserted_id: " + str(result.inserted_id)) instance1 = odps.run_sql(sql1) while(not instance1.is_successful()): time.sleep(1) plog("sql1 runs Successful") instance2 = odps.run_sql(sql2) while(not instance2.is_successful()): count += 1 progress = int((1.0 * count / (count + 1)) * 100) plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["compute_uuid_cell_hour"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) time.sleep(5) db_client.close() progress = 100 plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["compute_uuid_cell_hour"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) plog("result.matched_count: "+str(result.matched_count)) plog("result.modified_count: "+str(result.modified_count)) def post(self): # 解析输入的参数 self.project_id = self.get_argument('project_id'); # 构造阿里云上运行的sql sql1 = ('create table if not exists ' '' + self.project_id + '_uuid_cell_hour ' '(uuid string, cell_hour string)' 'partitioned by (date_p string);') sql2 = ('insert overwrite table ' '' + self.project_id + '_uuid_cell_hour ' 'partition(date_p) ' 'select uuid, ' 'agg_cell_hour(bs_id, datepart(from_unixtime(time), "HH")) as ' 'cell_hour, date_p from ' + self.project_id + '_filtered_raw_data ' 'group by uuid, date_p') plog("sql1: " + sql1) plog("sql2: " + sql2) # 调用阿里云执行sql BaseHandler.runSQL2(self, sql1, sql2, \ "compute_uuid_cell_hour", \ self.doComputeUuidCellHour) # 渲染结果页面 #self.render('compute_uuid_cell_hour_result.html', # project_id = self.project_id, # ret_msg = "Success") obj = {'project_id' : self.project_id, 'ret_msg' : "Success"} self.write(json_encode(obj)) # 19 class GetUuidCellHourHandler(tornado.web.RequestHandler, BaseHandler): def post(self): # 解析输入的参数 project_id = self.get_argument('project_id'); # 渲染结果页面 #self.render('get_uuid_cell_hour_result.html', # project_id = project_id, # result = project_id + "_uuid_cell_hour", # ret_msg = "Success") obj = {'project_id' : project_id, 'odps_table' : project_id + "_uuid_cell_hour", 'ret_msg' : "Success"} self.write(json_encode(obj)) # 20 class DeleteAllTablesHandler(tornado.web.RequestHandler, BaseHandler): def doDeleteAllTables(self, exe): name = multiprocessing.current_process().name plog(name + ": " + "Starting") db_client = MongoClient('localhost', 27017) db = db_client[self.project_id + "_db"] collection = db["task-progress"] progress = 0 result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["delete_all_tables"]}) result = collection.insert_one( { "project_id" : self.project_id, "task_id" : _task_id["delete_all_tables"], "progress" : progress, "lastModified" : datetime.datetime.utcnow() } ) count = 0 for line in BaseHandler.runProcess(self, exe): print line, if "OK" in line: count += 1 if count == 15: progress = 100 result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["delete_all_tables"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) plog(name + ": " + "Exiting") #delete all local meta data ## task-progress collection = db["task-progress"] ### create_customer_raw_data_table result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["create_customer_raw_data_table"]}) ### upload_customer_raw_data result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["upload_customer_raw_data"]}) ### transform_to_spatio_temporal_raw_data result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["transform_to_spatio_temporal_raw_data"]}) ### compute_raw_data_stat result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["compute_raw_data_stat"]}) ### compute_people_distribution result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["compute_people_distribution"]}) ### compute_base_station_info result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["compute_base_station_info"]}) ### download_base_station_info result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["download_base_station_info"]}) ### filter_data_with_range result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["filter_data_with_range"]}) ### compute_filtered_data_stat result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["compute_filtered_data_stat"]}) ### compute_base_station_hour_summary result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["compute_base_station_hour_summary"]}) ### download_base_station_hour_summary result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["download_base_station_hour_summary"]}) ### compute_uuid_cell_hour result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["compute_uuid_cell_hour"]}) ### compute_peo_roam result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["compute_peo_roam"]}) ### compute_peo_type result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["compute_peo_type"]}) ### compute_uuid_od result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["compute_uuid_od"]}) ### upload_area_station result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["upload_area_station"]}) ### compute_business_data result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["compute_business_data"]}) ### download_business_data result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["download_business_data"]}) ### delete_all_tables (remained) ## customer_fields collection = db["customer_fields"] ### create_customer_raw_data_table result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["create_customer_raw_data_table"]}) ## local-result collection = db["local-result"] ### compute_raw_data_stat result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["compute_raw_data_stat"]}) ### compute_people_distribution result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["compute_people_distribution"]}) ### filter_data_with_range result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["filter_data_with_range"]}) db_client.close() def post(self): self.project_id = self.get_argument('project_id'); plog("project_id: " + self.project_id) sql = "drop table if exists " + self.project_id + "_spatio_temporal_raw_data; " + \ "drop table if exists " + self.project_id + "_filtered_raw_data; " + \ "drop table if exists " + self.project_id + "_base_station_info; " + \ "drop table if exists " + self.project_id + "_base_station_hour_summary; " + \ "drop table if exists " + self.project_id + "_uuid_cell_hour; " +\ "drop table if exists " + self.project_id + "_peo_roam; " +\ "drop table if exists " + self.project_id + "_uuid_type; " +\ "drop table if exists " + self.project_id + "_uuid_od; " +\ "drop table if exists " + self.project_id + "_area_station; " +\ "drop table if exists " + self.project_id + "_area_od; " +\ "drop table if exists " + self.project_id + "_local_peo; " +\ "drop table if exists " + self.project_id + "_out_os; " +\ "drop table if exists " + self.project_id + "_peo_distr; " +\ "drop table if exists " + self.project_id + "_pass_local; " +\ "drop table if exists " + self.project_id + "_home_work; " BaseHandler.runCmd(self, sql, \ "delete_all_tables", self.doDeleteAllTables) obj = {'return_msg' : "Success"} self.write(json_encode(obj)) #30 class ComputePeopleRoamHandler(tornado.web.RequestHandler, BaseHandler): def doComputePeopleRoam(self, sql): # 调用后台阿里云后, 这里处理其返回结果 name = multiprocessing.current_process().name plog(name + " " + "Starting") progress = 0 # 建立数据库连接 db_client = MongoClient('localhost', 27017) db = db_client[self.project_id + "_db"] collection = db["task-progress"] count = 0; result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["compute_peo_roam"]}) result = collection.insert_one( { "project_id" : self.project_id, "task_id" : _task_id["compute_peo_roam"], "progress" : progress, "lastModified" : datetime.datetime.utcnow() } ) plog("result.inserted_id: " + str(result.inserted_id)) instance0 = odps.run_sql("drop table if exists " +self.project_id+"_peo_roam;") while(not instance0.is_successful()): time.sleep(2) plog("drop table SQL runs Successful") instance = odps.run_sql(sql) while(not instance.is_successful()): #plog("is_successful(): " + str(instance.is_successful())) #plog("is_terminated(): " + str(instance.is_terminated())) count += 1 progress = int((1.0 * count / (count + 1)) * 100) plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["compute_peo_roam"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) time.sleep(5) progress = 100 plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["compute_peo_roam"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) db_client.close() plog("result.matched_count: "+str(result.matched_count)) plog("result.modified_count: "+str(result.modified_count)) def post(self): # 解析输入的参数 self.project_id = self.get_argument('project_id'); # 构造阿里云上运行的sql sql = ('create table '+self.project_id+'_peo_roam as ' 'select uuid,is_roam from ' '( select uuid,is_roam,row_number()over(partition by uuid order by uuid) flag ' 'from ' +self.project_id + '_customer_raw_data ' ') t where flag=1 and uuid is not null and is_roam is not null;') plog("sql: " + sql) # 调用阿里云执行sql BaseHandler.runSQL(self, sql, \ "compute_peo_roam", self.doComputePeopleRoam) obj = {'project_id' : self.project_id, 'ret_msg' : "Performing"} self.write(json_encode(obj)) #31 class ComputePeopleTypeHandler(tornado.web.RequestHandler, BaseHandler): def doComputePeopleType(self, sql1, sql2): name = multiprocessing.current_process().name plog(name + " " + "Starting") progress = 0 # 建立数据库连接 db_client = MongoClient('localhost', 27017) db = db_client[self.project_id + "_db"] collection = db["task-progress"] count = 0; result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["compute_peo_type"]}) result = collection.insert_one( { "project_id" : self.project_id, "task_id" : _task_id["compute_peo_type"], "progress" : progress, "lastModified" : datetime.datetime.utcnow() } ) plog("result.inserted_id: " + str(result.inserted_id)) instance0 = odps.run_sql("drop table if exists " +self.project_id+"_uuid_type;") while(not instance0.is_successful()): time.sleep(2) plog("drop table SQL runs Successful") instance1 = odps.run_sql(sql1) while(not instance1.is_successful()): time.sleep(2) plog("sql1 runs Successful") ret = instance1.get_task_result(instance1.get_task_names()[0]) mydates = ret.split("\n")[1:-1] plog(mydates) daycount = 0 daywork = 0 for mydate in mydates: daycount+=1 if self.isWorkDay(mydate): daywork+=1 #replace parameter sql2r = sql2.replace('PARONE',str(daycount)).replace('PARTWO',str(daywork)) plog("compute people type SQL:-"+sql2r) instance2 = odps.run_sql(sql2r) while(not instance2.is_successful()): count += 1 progress = int((1.0 * count / (count + 1)) * 100) plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["compute_peo_type"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) time.sleep(5) progress = 100 plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["compute_peo_type"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) db_client.close() plog("result.matched_count: "+str(result.matched_count)) plog("result.modified_count: "+str(result.modified_count)) # 判断日期星期几 def isWorkDay(self,date_p): f_date=date_p[1:-1] year =f_date[0:4] month=f_date[4:6] day=f_date[6:8] t = datetime.date(int(year),int(month),int(day)) week = t.weekday() if week>4: return False return True def post(self): # 解析输入的参数 self.project_id = self.get_argument('project_id'); self.passvalue = self.get_argument('passvalue'); # 构造阿里云上运行的sql sql1 = ('select distinct date_p from '+self.project_id+'_uuid_cell_hour' ' where date_p is not null;') sql2=('create table '+self.project_id+'_uuid_type as ' 'select usertype(uuid,cell_hour,date_p,is_roam,PARONE,PARTWO,'+self.passvalue+') ' 'as (uuid,is_roam,cell_w,cell_h,p_t1,p_t2,p_t3,p_t4,p_t5,p_t6) from ( ' 'select t1.uuid,t1.cell_hour,t1.date_p,t2.is_roam from '+self.project_id+'_uuid_cell_hour t1 ' 'left outer join '+self.project_id+'_peo_roam t2 ' 'on t1.uuid=t2.uuid where t2.is_roam is not null ' 'distribute by uuid sort by uuid,date_p ) t ;') plog("sql: " + sql1) plog("sql: " + sql2) # 调用阿里云执行sql BaseHandler.runSQL2(self,sql1,sql2,"compute_peo_type",\ self.doComputePeopleType) obj = {'project_id' : self.project_id, 'ret_msg' : "Performing"} self.write(json_encode(obj)) #32 class ComputeODHandler(tornado.web.RequestHandler, BaseHandler): def doComputeOD(self, sql): # 调用后台阿里云后, 这里处理其返回结果 name = multiprocessing.current_process().name plog(name + " " + "Starting") progress = 0 # 建立数据库连接 db_client = MongoClient('localhost', 27017) db = db_client[self.project_id + "_db"] collection = db["task-progress"] count = 0 result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["compute_uuid_od"]}) result = collection.insert_one( { "project_id" : self.project_id, "task_id" : _task_id["compute_uuid_od"], "progress" : progress, "lastModified" : datetime.datetime.utcnow() } ) plog("result.inserted_id: " + str(result.inserted_id)) instance0 = odps.run_sql("drop table if exists " +self.project_id+"_uuid_od;") while(not instance0.is_successful()): time.sleep(2) plog("drop table SQL runs Successful") instance = odps.run_sql(sql) while(not instance.is_successful()): #plog("is_successful(): " + str(instance.is_successful())) #plog("is_terminated(): " + str(instance.is_terminated())) count += 1 progress = int((1.0 * count / (count + 1)) * 100) plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["compute_uuid_od"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) time.sleep(5) progress = 100 plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["compute_uuid_od"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) db_client.close() plog("result.matched_count: "+str(result.matched_count)) plog("result.modified_count: "+str(result.modified_count)) def post(self): # 解析输入的参数 self.project_id = self.get_argument('project_id'); # 构造阿里云上运行的sql sql = ('create table '+self.project_id+'_uuid_od as ' 'select od(uuid,cell_hour,date_p) as (uuid,time,oid,did,stayhour) ' 'from (select * from '+self.project_id+'_uuid_cell_hour ' 'distribute by uuid sort by uuid,date_p) d;') plog("sql: " + sql) # 调用阿里云执行sql BaseHandler.runSQL(self, sql, \ "compute_uuid_od", self.doComputeOD) # 渲染结果页面 obj = {'project_id' : self.project_id, 'ret_msg' : "Performing"} self.write(json_encode(obj)) # 33 class UploadCellAreaHandler(tornado.web.RequestHandler, BaseHandler): def doUploadCellArea(self, exe): name = multiprocessing.current_process().name plog(name+" "+"Starting") total = 0 finished = 0 progress = 0 session_id = "" db_client = MongoClient('localhost', 27017) db = db_client[self.project_id + "_db"] collection = db["task-progress"] instance0 = odps.run_sql("drop table if exists " +self.project_id+"_area_station;") while(not instance0.is_successful()): time.sleep(2) plog("drop table SQL runs Successful") sql=('create table if not exists '+self.project_id+'_area_station(' 'cid bigint,' 'area_tid bigint,' 'aid bigint);') instance = odps.run_sql(sql) while(not instance.is_successful()): time.sleep(1) plog("sql1 runs Successful") for line in BaseHandler.runProcess(self, exe): print line, # extract upload progess and total block if "Upload session" in line: session_id = line.split()[2] plog("session_id: " + session_id) result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["upload_area_station"]}) result = collection.insert_one( { "project_id" : self.project_id, "task_id" : _task_id["upload_area_station"], "aliyun_sess_id" : session_id, "progress" : progress, "lastModified" : datetime.datetime.utcnow() } ) plog("result.inserted_id: " + str(result.inserted_id)) if "Split input to" in line: total = int(line.split()[5]) plog("total: " + str(total)) elif "upload block complete" in line: finished += 1 plog("finished: " + str(finished)) progress = int((1.0 * finished / total) * 100) plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["upload_area_station"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) plog("result.matched_count: "+str(result.matched_count)) plog("result.modified_count: "+str(result.modified_count)) plog(name+" Exiting") db_client.close() def post(self): # 解析输入的参数 self.project_id = self.get_argument('project_id') #aliyun_table = self.get_argument('aliyun_table') aliyun_table = self.project_id + "_area_station" # 构造阿里云上运行的sql upload_cmd = "tunnel upload "+_download_folder+"/"+self.project_id+"_cellarea.txt " + aliyun_table +";" # 调用阿里云执行sql BaseHandler.runCmd(self, upload_cmd, "upload_area_station", self.doUploadCellArea) # 渲染结果页面 obj = {'project_id' : self.project_id, 'ret_msg' : "Performing"} self.write(json_encode(obj)) # 34 class ComputeBusinessDataHandler(tornado.web.RequestHandler, BaseHandler): def doComputeBusinessData(self, project_id): name = multiprocessing.current_process().name plog(name + " " + "Starting") progress = 0 # 建立数据库连接 db_client = MongoClient('localhost', 27017) db = db_client[self.project_id + "_db"] collection = db["task-progress"] count = 0; result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["compute_business_data"]}) result = collection.insert_one( { "project_id" : self.project_id, "task_id" : _task_id["compute_business_data"], "progress" : progress, "lastModified" : datetime.datetime.utcnow() } ) plog("result.inserted_id: " + str(result.inserted_id)) instance10 = odps.run_sql("drop table if exists " +self.project_id+"_area_od;") while(not instance10.is_successful()): time.sleep(2) plog("drop table SQL runs Successful") plog("________________________________________________________________________") sql1=('create table '+project_id+'_area_od as ' 'select b.aid area_oid,d.aid area_did,a.time,b.area_tid,' ' sum(c.p_t1) p_type1, sum(c.p_t2) p_type2, sum(c.p_t3) p_type3, sum(c.p_t4) p_type4, sum(c.p_t5) p_type5,' ' sum(c.p_t6) p_type6,' ' count(case when c.p_t1=0 and c.p_t2=0 and c.p_t3=0 and c.p_t4=0 and c.p_t5=0 and c.p_t6=0 then 1 end) p_type7' ' from '+project_id+'_uuid_od a left outer join '+project_id+'_uuid_type c on a.uuid=c.uuid' ' left outer join '+project_id+'_area_station b on a.oid=b.cid' ' left outer join '+project_id+'_area_station d on a.did=d.cid' ' where b.aid!=-1 and d.aid!=-1 ' ' group by b.aid,d.aid,a.time,b.area_tid; ') plog(sql1) instance1 = odps.run_sql(sql1) while(not instance1.is_successful()): count += 1 progress = int((1.0 * count / (count + 1)) * 100)/8 plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["compute_business_data"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) time.sleep(5) time.sleep(2) instance20 = odps.run_sql("drop table if exists " +self.project_id+"_out_os;") while(not instance20.is_successful()): time.sleep(2) plog("drop table SQL runs Successful") plog("________________________________________________________________________") sql2=('create table '+project_id+'_out_os as ' ' select b.lon,b.lat,a.time, ' ' sum(c.p_t1) p_type1,' ' sum(c.p_t2) p_type2,' ' sum(c.p_t3) p_type3,' ' sum(c.p_t4) p_type4,' ' sum(c.p_t5) p_type5,' ' sum(c.p_t6) p_type6,' ' sum(case when c.p_t1=0 and c.p_t2=0 and c.p_t3=0 and c.p_t4=0 and c.p_t5=0 and c.p_t6=0 then 1 else 0 end) p_type7 ' 'from '+project_id+'_uuid_od a ' 'left outer join '+project_id+'_base_station_info b on a.oid=b.id ' 'left outer join '+project_id+'_uuid_type c on a.uuid=c.uuid ' 'group by b.lon,b.lat,a.time;') plog(sql2) instance2 = odps.run_sql(sql2) while(not instance2.is_successful()): count += 1 progress = int((1.0 * count / (count + 1)) * 100)/7 plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["compute_business_data"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) time.sleep(5) time.sleep(2) #增加D的出行密度 instance70 = odps.run_sql("drop table if exists " +self.project_id+"_out_ds;") while(not instance70.is_successful()): time.sleep(2) plog("drop table SQL runs Successful") plog("________________________________________________________________________") sql7=('create table '+project_id+'_out_ds as ' ' select b.lon,b.lat,a.time, ' ' sum(c.p_t1) p_type1,' ' sum(c.p_t2) p_type2,' ' sum(c.p_t3) p_type3,' ' sum(c.p_t4) p_type4,' ' sum(c.p_t5) p_type5,' ' sum(c.p_t6) p_type6,' ' sum(case when c.p_t1=0 and c.p_t2=0 and c.p_t3=0 and c.p_t4=0 and c.p_t5=0 and c.p_t6=0 then 1 else 0 end) p_type7 ' 'from '+project_id+'_uuid_od a ' 'left outer join '+project_id+'_base_station_info b on a.did=b.id ' 'left outer join '+project_id+'_uuid_type c on a.uuid=c.uuid ' 'group by b.lon,b.lat,a.time;') plog(sql7) instance7 = odps.run_sql(sql7) while(not instance7.is_successful()): count += 1 progress = int((1.0 * count / (count + 1)) * 100)/6 plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["compute_business_data"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) time.sleep(5) time.sleep(2) #增加人群热度 instance80 = odps.run_sql("drop table if exists " +self.project_id+"_station_summary;") while(not instance80.is_successful()): time.sleep(2) plog("drop table SQL runs Successful") plog("________________________________________________________________________") sql8=('create table '+project_id+'_station_summary as ' ' select lon,lat,CONCAT(substr(from_unixtime(time),1,14),\'00:00\') as time, ' ' sum(c.p_t1) p_type1,' ' sum(c.p_t2) p_type2,' ' sum(c.p_t3) p_type3,' ' sum(c.p_t4) p_type4,' ' sum(c.p_t5) p_type5,' ' sum(c.p_t6) p_type6,' ' sum(case when c.p_t1=0 and c.p_t2=0 and c.p_t3=0 and c.p_t4=0 and c.p_t5=0 and c.p_t6=0 then 1 else 0 end) p_type7 ' 'from '+project_id+'_filtered_raw_data a ' 'left outer join '+project_id+'_uuid_type c on a.uuid=c.uuid ' 'group by lon, lat, substr(from_unixtime(time),1,14);') plog(sql8) instance8 = odps.run_sql(sql8) while(not instance8.is_successful()): count += 1 progress = int((1.0 * count / (count + 1)) * 100)/5 plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["compute_business_data"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) time.sleep(5) time.sleep(2) #local people instance30 = odps.run_sql("drop table if exists " +self.project_id+"_local_peo;") while(not instance30.is_successful()): time.sleep(2) plog("drop table SQL runs Successful") plog("________________________________________________________________________") sql3=('create table '+project_id+'_local_peo as ' 'select b.aid,b.area_tid,' ' sum(c.p_t1) p_type1,' ' sum(c.p_t2) p_type2,' ' sum(c.p_t3) p_type3,' ' sum(c.p_t4) p_type4,' ' sum(c.p_t5) p_type5,' ' sum(c.p_t6) p_type6,' ' sum(case when c.p_t1=0 and c.p_t2=0 and c.p_t3=0 and c.p_t4=0 and c.p_t5=0 and c.p_t6=0 then 1 else 0 end) p_type7' ' from '+project_id+'_uuid_type c ' ' left outer join '+project_id+'_area_station b on c.cell_h=b.cid ' ' where c.p_t1=1 and b.aid!=-1 ' ' group by b.aid,b.area_tid;') plog(sql3) instance3 = odps.run_sql(sql3) while(not instance3.is_successful()): count += 1 progress = int((1.0 * count / (count + 1)) * 100)/4 plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["compute_business_data"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) time.sleep(5) time.sleep(5) instance40 = odps.run_sql("drop table if exists " +self.project_id+"_peo_distr;") while(not instance40.is_successful()): time.sleep(2) plog("drop table SQL runs Successful") plog("________________________________________________________________________") sql4=('create table '+project_id+'_peo_distr as ' ' select b.aid,a.time,b.area_tid,' ' sum(c.p_t1) p_type1,' ' sum(c.p_t2) p_type2,' ' sum(c.p_t3) p_type3,' ' sum(c.p_t4) p_type4,' ' sum(c.p_t5) p_type5,' ' sum(c.p_t6) p_type6,' ' count(case when c.p_t1=0 and c.p_t2=0 and c.p_t3=0 and c.p_t4=0 and c.p_t5=0 and c.p_t6=0 then 1 end) p_type7' ' from '+project_id+'_uuid_od a' ' left outer join '+project_id+'_uuid_type c on a.uuid=c.uuid' ' left outer join '+project_id+'_area_station b on a.oid=b.cid' ' where b.aid!=-1' ' group by b.aid,a.time,b.area_tid;') plog(sql4) instance4 = odps.run_sql(sql4) while(not instance4.is_successful()): count += 1 progress = int((1.0 * count / (count + 1)) * 100)/3 plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["compute_business_data"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) time.sleep(5) time.sleep(5) instance50 = odps.run_sql("drop table if exists " +self.project_id+"_pass_local;") while(not instance50.is_successful()): time.sleep(2) plog("drop table SQL runs Successful") plog("________________________________________________________________________") sql5=('create table '+project_id+'_pass_local as ' ' select substr(time,1,10) time,count(distinct a.uuid) pcount' ' from '+project_id+'_uuid_od a' ' left outer join '+project_id+'_uuid_type c on a.uuid=c.uuid' ' where c.p_t5=1 group by substr(time,1,10);') plog(sql5) instance5 = odps.run_sql(sql5) while(not instance5.is_successful()): count += 1 progress = int((1.5 * count / (count + 1)) * 100)/2 plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["compute_business_data"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) time.sleep(5) time.sleep(5) instance60 = odps.run_sql("drop table if exists " +self.project_id+"_home_work;") while(not instance60.is_successful()): time.sleep(2) plog("drop table SQL runs Successful") plog("________________________________________________________________________") sql6=('create table '+project_id+'_home_work as ' 'select b.aid area_hid,c.aid area_wid,b.area_tid,count(*) pcount' ' from '+project_id+'_uuid_type a ' ' left outer join '+project_id+'_area_station b on a.cell_h=b.cid' ' left outer join '+project_id+'_area_station c on a.cell_w=c.cid' ' where a.cell_h!=0 and a.cell_w!=0 and b.aid!=-1 and c.aid!=-1' ' group by b.aid,c.aid,b.area_tid;') plog(sql6) instance6 = odps.run_sql(sql6) while(not instance6.is_successful()): count += 1 progress = int((1.0 * count / (count + 1)) * 100) plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["compute_business_data"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) time.sleep(5) plog("________________________________________________________________________") progress = 100 plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["compute_business_data"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) db_client.close() plog("result.matched_count: "+str(result.matched_count)) plog("result.modified_count: "+str(result.modified_count)) def post(self): # 解析输入的参数 self.project_id = self.get_argument('project_id'); # 调用阿里云执行sql BaseHandler.runSQL(self,self.project_id,"compute_business_data",\ self.doComputeBusinessData) # 渲染结果页面 obj = {'project_id' : self.project_id, 'ret_msg' : "Performing"} self.write(json_encode(obj)) # 35 class DownloadBusinessDataHandler(tornado.web.RequestHandler, BaseHandler): def doDownloadBusinessData(self, exe): with self.lock: name = multiprocessing.current_process().name plog(name + " " + "Starting") progress = 0 db_client = MongoClient('localhost', 27017) db = db_client[self.project_id + "_db"] collection = db["task-progress"] result = collection.delete_many({ "project_id": self.project_id, "task_id": _task_id["download_business_data"]}) result = collection.insert_one( { "project_id" : self.project_id, "task_id" : _task_id["download_business_data"], "progress" : progress, "lastModified" : datetime.datetime.utcnow() } ) for line in BaseHandler.runProcess(self, exe): print line, # extract upload progess and total block if "download OK" in line: self.sums.value+=1 plog(" There are "+str(self.sums.value)+" tasks done...") if self.sums.value == self.lenoftab: progress = 100 plog("progress: " + str(progress) + "%") result = collection.update_one( {"project_id" : self.project_id, "task_id" : _task_id["download_business_data"] }, { "$set": { "progress": progress }, "$currentDate": {"lastModified": True} } ) plog("all download was done, "+name+" Exiting") db_client.close() def post(self): # 解析输入的参数 self.project_id = self.get_argument('project_id'); tables=['_area_od','_out_os','_out_ds','_station_summary','_local_peo','_peo_distr','_pass_local','_home_work'] self.lenoftab=len(tables) self.lock = multiprocessing.Lock() self.manager = multiprocessing.Manager() self.sums = self.manager.Value('tmp', 0) for table in tables: table_name=self.project_id+table # 构造阿里云上运行的cmd download_cmd = ('tunnel download ' + table_name + ' ' + _download_folder + '/' + table_name + '.csv ' '-h true;') plog("download_cmd: " + download_cmd) BaseHandler.runCmd(self, download_cmd, "download_business_data", \ self.doDownloadBusinessData) # 渲染结果页面 obj = {'project_id' : self.project_id, 'ret_msg' : "Performing"} self.write(json_encode(obj)) if __name__ == '__main__': tornado.options.parse_command_line() http_server = tornado.httpserver.HTTPServer(Application()) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start() <file_sep>/src/odps/odps-console-dship/src/test/resources/odps_config.ini project_name= access_id= access_key= end_point= <file_sep>/doc/增加json输出.md # 增加json输出 把现有的输出换成json格式, 输出基于json_encode 需要用json decode解析,因为可能有中文等字符 简单测试可以用: http://json.parser.online.fr/ 如果返回的是英文, 则直接可以看到 <file_sep>/src/odps/odps_config.ini project_name=tsnav_project access_id=<KEY> access_key=<KEY> end_point=http://service.odps.aliyun.com/api tunnel_endpoint=http://dt.odps.aliyun.com log_view_host=http://logview.odps.aliyun.com https_check=true <file_sep>/doc/一键删除.md # 一键删除所有表 drop table if exists test_nanjing_1_customer_raw_data; drop table if exists test_nanjing_1_spatio_temporal_raw_data; drop table if exists test_nanjing_1_base_station_info; drop table if exists test_nanjing_1_base_station_hour_summary; drop table if exists test_nanjing_1_uuid_cell_hour; <file_sep>/doc/任务进度查询.md # 任务进度查询 所有任务在云端执行都会返回执行进度, 在任务启动后需要通过相应的API接口获取任务进行进度, 所有的进度类查询都使用同一个api接口, 输入参数是项目id, 以及任务id, 会返回此任务当前的执行进度。 ``` /request_task_progress ``` ## 参数 1. project_id 2. task_id ### task_id定义 1. create_customer_raw_data_table: 监理客户原始格式数据表结构 2. upload_customer_raw_data: 上传客户原始格式数据 3. transform_to_spatio_temporal_raw_data: 转换成内部数据表结构 4. compute_people_distribution: 计算人基于数据量的分布情况
225fa17ad5d8cbc91d457bfea8bd1a43f43ebcc7
[ "Markdown", "Python", "INI" ]
7
INI
wang-yang/cell_signalling_analysis
f3c8f320fa87cc68a3b4cd26325191f23bbe4706
2e90e53981bdea7186d0db413e488b6a3eded281
refs/heads/master
<repo_name>B-pea/LinkList-practise<file_sep>/LinkList.cpp //链表的主要操作 创建、删除、插入、输出、排序、反序、销毁 #include<stdlib.h> #include<stdio.h> #include <iostream> using namespace std; typedef struct node { int data; struct node* next; }*LinkList; LinkList head = NULL; bool create_new(int data) //创建新表头 { head = (LinkList)malloc(sizeof(node)); if (head == NULL) { return false; } head->data = data; head->next = NULL; return true; } bool add_node(int data,LinkList head) //增加链表长度,表尾插入 { if (head == NULL) { return false; } LinkList new_node; new_node = (LinkList) malloc(sizeof(node)); if (new_node == NULL) { return false; } new_node->data = data; new_node->next = NULL; while(head->next != NULL) { head = head->next; } head->next = new_node; return true; } bool insert_node(int data,LinkList head,int index) //以值为索引的中间插入,索引之前 { if (head == NULL) { return false; } LinkList insert_node; insert_node = (LinkList)malloc(sizeof(node)); if (insert_node == NULL) { return false; } insert_node->data = data; LinkList temp_node; temp_node = (LinkList)malloc(sizeof(node)); if (temp_node == NULL) { return false; } temp_node = head; while(temp_node->next->data!=index && temp_node->next->next!=NULL) { temp_node = temp_node->next; } if (temp_node->next->data !=index && temp_node->next->next == NULL) { cout<<"index is not include!"<<endl; return false; } insert_node->next = temp_node->next; temp_node->next = insert_node; return true; } bool delete_node(int index,LinkList head) { if (head == NULL) { return false; } LinkList temp_node = (LinkList)malloc(sizeof(node)); if (temp_node == NULL) { return false; } temp_node = head; while(temp_node->next->data!=index && temp_node->next!=NULL) { int i = temp_node->next->data; temp_node = temp_node->next; } LinkList delete_node = (LinkList)malloc(sizeof(node)); if (delete_node == NULL) { return false; } delete_node = temp_node->next; temp_node->next = delete_node->next; free(delete_node); return true; } bool out_list(LinkList head) { if (head == NULL) { return false; } //LinkList temp_node = (LinkList)malloc(sizeof(node)); //if (temp_node == NULL) //{ // return false; //} //temp_node = head; while(head!=NULL) { cout<<head->data<<endl; head = head->next; } cout<<endl; return true; } bool sort_list(LinkList head) { LinkList first_temp = (LinkList)malloc(sizeof(node)); LinkList next_temp = (LinkList)malloc(sizeof(node)); if (first_temp == NULL && next_temp == NULL) { return false; } first_temp = head; int length_list = 0; while(first_temp!=NULL) { length_list++; first_temp = first_temp->next; } first_temp = head; int j = 0; int length_no = length_list; for (j;j<length_list;j++) { next_temp = first_temp->next; for (int i=0;i<length_no-1;i++) { int temp_data; if (first_temp->data > next_temp->data) { temp_data = next_temp->data; next_temp->data = first_temp->data; first_temp->data =temp_data; out_list(head); cout<<j<<endl; cout<<endl; } next_temp = next_temp->next; } first_temp = first_temp->next; length_no--; } return true; } void main () { create_new(1); for (int i = 2;i<10;i++) { add_node(i,head); } delete_node(4,head); insert_node(99,head,3); out_list(head); cout<<endl; sort_list(head); out_list(head); }
daf23b6b1340fe24bb8df6c57bd8f610bb430702
[ "C++" ]
1
C++
B-pea/LinkList-practise
17743f41d1b5d21d02e978ea67e55c8f7fd046bc
888e182108b7e7865d19a7566ad35c5475ca564d
refs/heads/master
<file_sep>const bing = require("../../libraries/bing.js"); const hefengWeather = require("../../libraries/hefengWeather.js"); const doubanMovie = require("../../libraries/doubanMovie.js"); const one = require("../../libraries/one.js"); var App = getApp(); var that = this; Page({ data: { //顶部轮播图片 images: [], //天气栏目 weatherLocation: "珠海市", weatherInfo: [], //电影栏目 moviesInTheaters: [], moviesComingSoon: [], //阅读栏目 dateIndex: 0, idList: [], oneList: [], //分栏bar navList: [{ id: 0, title: "天气", isCurr: true, hasLoad: false, }, { id: 1, title: "电影", isCurr: false, hasLoad: false, }, { id: 2, title: "阅读", isCurr: false, hasLoad: false, } // , { // id: 3, // title: "设置", // isCurr: false, // } ], index: 0, }, onLoad: function(o) { this.getDailyWallPaper(); this.loadTab(); //遍历分页数组检测当天打开的tab页加载内容 }, /*获取页面内容 */ getDailyWallPaper: function() { //从Bing API获取DailyWallPaper数据,url、title存入data的images数组中 var that = this; wx.request({ url: bing.DailyWallPager(), success: (res) => { // console.log(res.data.images + " ," + res.header + " ," + res.statusCode) if (res.statusCode == 200) { let resource = res.data.images; let list = [], url, title; for (let i = 0; i < resource.length; i++) { url = "http://www.bing.com/" + res.data.images[i].url; title = res.data.images[i].copyright; // console.log("url: " + url + " title: " + title); list.push({ url, title }); } that.setData({ //写入data images: list }) console.log("====bing每日图片获取成功====") } }, fail: (res) => { App.showToast("Bing每日图加载失败", 1000) } }) }, getWether: function(location) { //根据城市名"珠海市"获取天气 var that = this; wx.request({ url: hefengWeather.weather_now(location), success: (res) => { if (res.statusCode == 200) { // console.log(res.data.HeWeather6[0].now) let weatherInfo = res.data.HeWeather6[0].now; this.setData({ "weatherInfo": weatherInfo }) console.log("====getWether成功====" + res.statusCode) App.showToast('天气刷新成功', "success", 500); } else { App.showToast('天气获取失败'); } } }) }, cityChange: function(e) { //通过picker取得地址,调用getWeather刷新天气 console.log("cityChange.value:" + e.detail.value) let location = e.detail.value.slice(2); //将返回的字符串分割,只取最后 console.log("location:" + location) this.setData({ "weatherLocation": e.detail.value, }) this.getWether(location) }, getMovieInfo: function(movieInfoType) { //取得电影列表 console.log("getMovieInfo:" + doubanMovie.doubanMovie(movieInfoType)) wx.request({ url: doubanMovie.doubanMovie(movieInfoType), header: { "Content-Type": "json" }, data: { city: "珠海" }, success: (res) => { //console.log("getMovieInfo success: " + res.data.subjects) switch (movieInfoType) { case "in_theaters": this.setData({ "moviesInTheaters": res.data.subjects }); break; case "coming_soon": this.setData({ "moviesComingSoon": res.data.subjects }); break; } } }) }, navigateToDetail_movie: function(e) { //携带电影ID跳转到电影详情页 //console.log("e.currentTarget.dataset.movieId: "+e.currentTarget.dataset.movieId); let movieId = e.currentTarget.dataset.movieId; wx.navigateTo({ url: '../movieDetail/movieDetail?movieId=' + movieId, }) }, getIdList: function() { //取得id列表,更新文章列表 var that = this; let dateIndex = this.data.dateIndex; //console.log("===getIdList: dateIndex: " + dateIndex) one.IdList().then((idList) => { console.log("===test.js idList: " + idList) this.setData({ "idList": idList, }) }).then(() => { that.getOneList(dateIndex); }) }, getOneList: function(dateIndex) { //取得文章列表 let idList = this.data.idList[0]; //console.log("===test.js getOneList: " + idList); one.OneList(idList[dateIndex]).then((oneList) => { console.log("===test.js getOneList: '获取文章列表成功'" + oneList) this.setData({ "oneList": oneList, }) }) }, navigateToDetail_read: function(e) { //携带dataset contentId跳转到文章详情页 // console.log("navigateToDetail_read: " + e.currentTarget.dataset.contentId) let contentId = e.currentTarget.dataset.contentId; wx.navigateTo({ url: '/pages/readDetail/readDetail?contentId=' + contentId, }) }, changePostDate: function(e) { //改变dateIndex刷新文章列表 var that = this; let direction = e.currentTarget.dataset.direction; let dateIndex = this.data.dateIndex; let length = this.data.idList[0].length; console.log("direction:" + direction); console.log("length:" + length); switch (direction) { case "go": if (dateIndex <= length && dateIndex > 0) { dateIndex -= 1; console.log("datebtnTap: dateIndex-=1"); this.setData({ "dateIndex": dateIndex }) that.getOneList(dateIndex); } else { App.showToast("已经是最新的文章。", "none") } break; case "back": if (dateIndex < length - 1) { dateIndex += 1; console.log("datebtnTap: dateIndex+=1"); this.setData({ "dateIndex": dateIndex }) that.getOneList(dateIndex); } else { App.showToast("已经是最早的文章。", "none") } break; } console.log("dateIndex: " + dateIndex) }, /*分栏相关 */ navBarTap: function(e) { //navBar切换 this.changeIndex(e); }, navListItemChange: function(e) { this.changeIndex(e); }, changeIndex: function(e) { //navBar和swiper同步改变 let list = this.data.navList; let index; if (e.type == "tap") { //取得index index = e.target.id; } else if (e.type == "change") { index = e.detail.current } if (index != this.data.index) { //如果index改变了,更新navList for (let i = 0; i < list.length; i++) { list[i].isCurr = false; } list[index].isCurr = true; } this.setData({ "navList": list, "index": index, }) this.loadTab(); }, loadTab: function() { //切换分栏时检测tab页是否加载 var that = this; let navList = this.data.navList; //console.log("===loadTab: navList: " + navList) for (let i = 0; i < navList.length; i++) { //console.log("===loadTab: navList[i].hasLoad: " + navList[i].hasLoad) if (navList[i].isCurr == true && navList[i].hasLoad == false) { navList[i].hasLoad = true; switch (i) { case 0: that.getWether(this.data.weatherLocation); break; case 1: that.getMovieInfo("in_theaters"); that.getMovieInfo("coming_soon"); break; case 2: that.getIdList(); break; } } } that.setData({ "navList": navList, }) } }) <file_sep>const one = require("../../libraries/one.js"); var WxParse = require('../components/wxParse/wxParse.js'); //富文本解析自定义组件 Page({ data: { contentInfo: [], }, onLoad(option) { //console.log("readDetail.js option.contentId:" + option.contentId); this.getContentInfo(option.contentId); }, getContentInfo: function(contentId) { //根据传入的contentId请求文章 one.ContentInfo(contentId).then((contentInfo) => { //console.log("readDetail.js contentInfo: " + contentInfo) this.setData({ "contentInfo": contentInfo, }) }).then(() => { let html = this.data.contentInfo[0].hp_content; this.resolveHtml(html) }) // .then(() => { //动态设置navigationBarTitleText // let title = this.data.contentInfo[0].hp_title // wx.setNavigationBarTitle({ // title: '《' + title + '》', // }) // }) }, resolveHtml: function(html) { //将HTML解析为WXML //console.log("resolveHtml html:" + html) var article = html; var that = this; WxParse.wxParse('article', 'html', article, that, 5); } })<file_sep>const doubanMovie = require("../../libraries/doubanMovie.js"); Page({ data: { movieId: "", movieInfo: [], trailers: [],//预告片数组 trailerIndex: 0, }, onLoad(option) { //console.log("option.movieId" + option.movieId) this.getMovieInfo(option.movieId); // this.videoContext = wx.createVideoContext("trailer"); }, getMovieInfo: function(movieId) { let url = doubanMovie.doubanMovie("subject") + "/" + movieId; console.log("url: " + url) wx.request({ url: url, header: { "Content-Type": "json" }, success: (res) => { if (res.statusCode == 200) { let list = []; list.push(res.data) this.setData({ "movieInfo": list }); // this.setData({ // "trailers": this.data.movieInfo[0].trailer_urls // }); wx.setNavigationBarTitle({ title: "《" + this.data.movieInfo[0].title + "》", }) } else { wx.showToast({ title: '获取电影列表失败 stautsCode:' + res.statusCode, duration: 1000, }) } } }) } })<file_sep>const app = getApp(); Page({ data: { longitude: 113.523047, latitude: 22.301141, showLocation: true, scale: 18, markers: [{ id: 1, longitude: 113.526105, latitude: 22.308397, title: "东坑老鹅村", }], showflag: true, showmap:false }, /** * 生命周期函数--监听页面加载 */ onLoad: function(options) { this.mapContext = wx.createMapContext("map"); }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function() { }, showTheMap:function(e){ this.setData({ showmap:!this.data.showmap }) console.log(this.data.showmap) }, hd1: function(e) { var that = this wx.getSetting({ success: (res) => { console.log("hd1:" + res.authSetting["scope.userLocation"]) if (res.authSetting["scope.userLocation"]) { that.setData({ showflag: !res.authSetting["scope.userLocation"] }) } } }) }, changeScale: function(e) { console.log(e.detail.value) this.setData({ scale: e.detail.value }) }, getLocation: function(e) { console.log("getlocation"); var that = this; wx.getSetting({ success: (res) => { console.log(res.authSetting["scope.userLocation"]); if (res.authSetting["scope.userLocation"]) { wx.getLocation({ type: "gcj02", success: function(res) { that.setData({ longitude: res.longitude, latitude: res.latitude }) }, fail: function(e) { console.log(e.errMsg) } }) } else { that.setData({ showflag: !res.authSetting["scope.userLocation"] }) wx.showToast({ title: '地理位置没有授权', duration: 3000, icon: "none" }) } } }) }, chooseLocation: function(e) { console.log("chooselocation") wx.chooseLocation({ success: function(res) { console.log("name:" + res.name + " address:" + res.address + " longitude:" + res.longitude + " latitude:" + res.latitude) }, fail: function(e) { console.log(e.errMsg) if (e.errMsg == "chooseLocation:fail auth deny") { wx.showToast({ title: '地理位置没有授权', duration: 3000, icon: "none" }) } } }) }, openLocation: function(e) { console.log("openlocation"); wx.openLocation({ latitude: 22.282662, longitude: 113.515634, name: "羽生创作料理", address: "奥园广场" }) }, moveToLocation: function(e) { console.log("getCenterLocation"); this.mapContext.moveToLocation(); }, getCenterLocation: function(e) { console.log("getCenterLocation"); this.mapContext.getCenterLocation({ success: (res) => { console.log(res.longitude + " ," + res.latitude) wx.showToast({ title: res.longitude + " ," + res.latitude, icon: 'none', duration: 1000 }) } }) }, getRegion: function(e) { console.log("getRegion"); this.mapContext.getRegion({ success: (res) => { var txt = res.southwest.longitude + " ," + res.southwest.latitude + " ; " + res.northeast.longitude + " ," + res.northeast.latitude; console.log(txt) wx.showToast({ title: txt, icon: 'none', duration: 2000 }) } }) }, getScale: function(e) { console.log("getScale"); this.mapContext.getScale({ success: (res) => { console.log(res.scale) wx.showToast({ title: "" + res.scale, icon: 'none', duration: 1000 }) } }) } })<file_sep>let API_URL = "https://api.douban.com/v2/movie/"; let API_URL1 ="https://douban.uieee.com/v2/movie/"; //某大佬搭建的代理,可用 module.exports = { doubanMovie: function(infoType) { let url = API_URL1 + infoType; return url } }<file_sep>let API_URL = "http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&"; // n = The no of images u want(u can use Integers), // mkt = Your location(example:zh-CN、en-US) module.exports = { DailyWallPager: function(n = 8, mkt = "zh-CN") { let url = API_URL + "n=" + n + "&mkt=" + mkt; return url } }
6042620371c2ecf507864811bcb40ab199b2e634
[ "JavaScript" ]
6
JavaScript
595105530/wechat-demo
4feeb51328c00e112aacb805a1addaf72266d9d5
1b682b0515f422f1b952a7fdb4cf404d96c89e9e
refs/heads/main
<repo_name>vers-dev/azimut<file_sep>/js/app.js const burgerMenu = document.querySelector(".header-trigger"); const menu = document.querySelector(".header-menu"); const closeMenu = document.querySelector(".header-menu__close"); burgerMenu.addEventListener("click", () => { menu.classList.add("show"); }); closeMenu.addEventListener("click", () => { menu.classList.remove('show'); });
a2dc7fa9372cc4bc2bf2988a4c1d646045feb555
[ "JavaScript" ]
1
JavaScript
vers-dev/azimut
71be79ffef69d40b8fc1231a203cae0662a58c69
e769024507a1af82a736b91690b5cf8f4a4beb0b
refs/heads/master
<repo_name>churellano/minigames-console<file_sep>/ext_buttons.h // ext_buttons.h // Routines/definitions for 3 external push buttons // by <NAME> #ifndef EXT_BUTTONS_H #define EXT_BUTTONS_H #include <stdbool.h> #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <time.h> //------- Enums and definitions -------------------- // Push-buttons enum extPushButton { PUSHBUTTON_SELECT = 0, PUSHBUTTON_ENTER_EXIT, PUSH_MAXBUTTONS }; //------- function prototypes ---------------------- // Initialize external push-buttons. void extPushButtonInit (); // Must be called before using functions // Check if a button is pushed. // Return value: true = pushed, false = not pushed, or unsuccessful file I/O. // _Bool extPushButtonPushed (enum extPushButton button); // Check if a button is pressed ("not pushed" to "pushed"). // Return value: true = pressed, false = not pressed // _Bool extPushButtonPressed (enum extPushButton button); // Check if a button is released ("pushed" to "not pushed"). // Return value: true = released, false = not released // _Bool extPushButtonReleased (enum extPushButton button); // Get name string of button const char *extPushButtonName (enum extPushButton button); #endif <file_sep>/zen_segdisplay.h // zen_segdisplay.h // Routines/definitions for Zen Cape's 2x15-segment LED display #ifndef ZEN_SEGDISPLAY_H #define ZEN_SEGDISPLAY_H #include <stdbool.h> #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <sys/ioctl.h> #include <linux/i2c.h> #include <linux/i2c-dev.h> #include <sys/types.h> #include <sys/stat.h> #include <time.h> #include <pthread.h> //------- Enums and definitions -------------------- // Selection of left/right digit enum zenSegDigit { SEGDIGIT_LEFT = 0, SEGDIGIT_RIGHT, SEGDIGIT_BOTH }; //------- function prototypes ---------------------- // Initializes 2-digit x 15-segment LED display // Return value: true=success, false=fail // _Bool zenSegDisplayInit(); // Must be called before using functions // Turn on 15-segment digits // Return value: true=success, false=fail // //_Bool zenSegDisplayDigitOn(enum zenSegDigit digit); // Turn off 15-segment digits // Return value: true=success, false=fail // //_Bool zenSegDisplayDigitOff(enum zenSegDigit digit); // Display a numeric digit. // 0 <= num <= 9. // Return value: true=success, false=fail // //_Bool zenSegDisplayNumDigit(int num); void zenSegDisplayUpdateNum(int newNum); void zenSegDisplayStart(); void zenSegDisplayStop(); #endif <file_sep>/catchGame.h // catchGame.h // Module to start/stop the "Catch" game thread and provide routines to retrieve game data. #ifndef _CATCHGAME_H_ #define _CATCHGAME_H_ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <pthread.h> #include <netdb.h> #include <string.h> #include <unistd.h> #include <time.h> #include "zen_joystick.h" #include "zen_buzzer.h" #include "ext_8x8led.h" #include "zen_segdisplay.h" //------- function prototypes ---------------------- // Start the game thread // void catchGame_start(void); // Stop the game thread // void catchGame_stop(void); // Get game data // *attempt = number of balls dropped // *catch = number of balls caught // *ballx = current ball X position (0 to 7), 0 is leftmost, 7 is rightmost LED dot // *bally = current ball Y position (0 to 7), 0 is uppermost, 7 is lowermost LED dot // *catchx = current catcher X position (0 to 7), 0 is leftmost, 7 is rightmost LED dot // (catcher Y position is fixed at 7) // void catchGame_GetData(int *attempt, int *catch, int *ballx, int *bally, int *catchx); #endif <file_sep>/snakeGame.c // snakeGame.c // Module to start/stop the "Snake" game thread and provide routines to retrieve game data. #include "snakeGame.h" //------------ variables and definitions ----------------------- #define SNAKEBODY_LENGTH 4 static pthread_t snakeGame_id; static pthread_mutex_t snakeGameStat = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t snakeGameData = PTHREAD_MUTEX_INITIALIZER; static snakegame_coords snakebody[SNAKEBODY_LENGTH]; // coordinates of snake's body (pixels) static snakegame_coords apple; // coordinate of apple (to be eaten by snake) static int apples_consumed = 0; static _Bool snake_in_motion = false; static _Bool gameStopped = false; static enum zenJoystickButton current_direction; extern unsigned char font8x8[]; //------------ functions --------------------------------------- //***** static functions ****************************** static void drawSnakeBody() { for (int k = 0; k < SNAKEBODY_LENGTH; k++) extLED8x8DrawPixel(snakebody[k].x, snakebody[k].y, 1); } static void generateNextAppleCoord() { int k; pthread_mutex_lock(&snakeGameData); { while(1) { // Generate random coordinate for apple apple.x = rand() % 8; apple.y = rand() % 8; for (k = 0; k < SNAKEBODY_LENGTH; k++) { // Check for conflicts with snake's body pixel locations if (k == 0) { // head if (((apple.x >= snakebody[k].x) && ((apple.x - snakebody[k].x) < 2)) || ((apple.x < snakebody[k].x) && ((snakebody[k].x - apple.x) < 2)) || ((apple.y >= snakebody[k].y) && ((apple.y - snakebody[k].y) < 2)) || ((apple.y < snakebody[k].y) && ((snakebody[k].y - apple.y) < 2))) break; } else { if ((apple.x == snakebody[k].x) || (apple.y == snakebody[k].y)) break; } } if (k == SNAKEBODY_LENGTH) // No conflicts with body break; } } pthread_mutex_unlock(&snakeGameData); } static void initSnakeBody() { pthread_mutex_lock(&snakeGameData); { snakebody[0].x = 4; // head snakebody[0].y = 3; snakebody[1].x = 3; snakebody[1].y = 3; snakebody[2].x = 2; snakebody[2].y = 3; snakebody[3].x = 1; snakebody[3].y = 3; } pthread_mutex_unlock(&snakeGameData); } static void moveSnake(enum zenJoystickButton button) { pthread_mutex_lock(&snakeGameData); { snakebody[3].x = snakebody[2].x; snakebody[3].y = snakebody[2].y; snakebody[2].x = snakebody[1].x; snakebody[2].y = snakebody[1].y; snakebody[1].x = snakebody[0].x; snakebody[1].y = snakebody[0].y; if (button == JOYSTICK_RIGHT) { snakebody[0].x++; } else if (button == JOYSTICK_LEFT) { snakebody[0].x--; } else if (button == JOYSTICK_UP) { snakebody[0].y--; } else { snakebody[0].y++; } } pthread_mutex_unlock(&snakeGameData); } static enum zenJoystickButton BannedDirection(enum zenJoystickButton button) { if (button == JOYSTICK_RIGHT) { return(JOYSTICK_LEFT); } else if (button == JOYSTICK_LEFT) { return(JOYSTICK_RIGHT); } else if (button == JOYSTICK_UP) { return(JOYSTICK_DOWN); } else { return(JOYSTICK_UP); } } //------------------------------------------------------- // "Balance the ball" game. //------------------------------------------------------- static void *snakeGameThread() { struct timespec reqDelay; enum zenJoystickButton button; int samplecnt; apples_consumed = 0; gameStopped = false; snake_in_motion = false; // Initialize snake's body initSnakeBody(); // Draw ball in center of matrix generateNextAppleCoord(); extLED8x8FillPixel(0); drawSnakeBody(); extLED8x8DrawPixel(apple.x, apple.y, 1); extLED8x8DisplayUpdate(); // Initialize score on seg display zenSegDisplayUpdateNum(apples_consumed); reqDelay.tv_sec = 0; reqDelay.tv_nsec = 10000000; // sampling rate while (1) { // Sample all joystick buttons for (button = JOYSTICK_UP; button < JOYSTICK_MAXBUTTONS; button++) { if (zenJoystickButtonPushed (button)) { break; } } if (gameStopped == false) { if (snake_in_motion == false) { if ((button < JOYSTICK_MAXBUTTONS) && (button != BannedDirection(JOYSTICK_RIGHT))) { moveSnake(button); extLED8x8FillPixel(0); drawSnakeBody(); extLED8x8DrawPixel(apple.x, apple.y, 1); extLED8x8DisplayUpdate(); snake_in_motion = true; samplecnt = 0; current_direction = button; } } else { if ((button < JOYSTICK_MAXBUTTONS) && (button != BannedDirection(current_direction))) { current_direction = button; } if (++samplecnt == 35) { samplecnt = 0; if (((snakebody[0].x == 7) && (current_direction == JOYSTICK_RIGHT)) || ((snakebody[0].x == 0) && (current_direction == JOYSTICK_LEFT)) || ((snakebody[0].y == 0) && (current_direction == JOYSTICK_UP)) || ((snakebody[0].y == 7) && (current_direction == JOYSTICK_DOWN))) { zenBuzzerBeep(110, 300); extLED8x8ScrollText(" Game Over!X", font8x8, 25, SCROLL_LEFT); gameStopped = true; } else { moveSnake(current_direction); extLED8x8FillPixel(0); drawSnakeBody(); if ((snakebody[0].x == apple.x) && (snakebody[0].y == apple.y)) { apples_consumed++; generateNextAppleCoord(); printf("Apples eaten: %d\n", apples_consumed); zenSegDisplayUpdateNum(apples_consumed); // Update score to seg display zenBuzzerBeep(440, 100); } extLED8x8DrawPixel(apple.x, apple.y, 1); extLED8x8DisplayUpdate(); } } } } // sampling delay nanosleep(&reqDelay, (struct timespec *) NULL); // Check for request to terminate thread int lockstat; lockstat = pthread_mutex_trylock(&snakeGameStat); if (lockstat == 0) { // lock acquired (0) means terminate pthread_exit(0); } } pthread_exit(0); } //***** public functions ****************************** void snakeGame_start (void) { printf("Starting game of 'Snake'\n"); // 3, 2, 1 count down extLED8x8CountDown321(font8x8); pthread_mutex_init(&snakeGameStat, NULL); // Lock mutex used by thread to check for request to end the thread pthread_mutex_lock(&snakeGameStat); // Start the thread pthread_create(&snakeGame_id, NULL, &snakeGameThread, NULL); } void snakeGame_stop (void) { // Unlock mutex to let sorting thread know about request to finish pthread_mutex_unlock(&snakeGameStat); printf("Stopping game of 'Snake'\n"); // Exit game logo extLED8x8ExitGame(font8x8); // Wait for thread to finish pthread_join(snakeGame_id, NULL); } void snakeGame_GetData (int *snakebody_length, snakegame_coords *snakebodycoords, snakegame_coords *applecoord, int *apples_eaten) { pthread_mutex_lock(&snakeGameData); { *apples_eaten = apples_consumed; applecoord->x = apple.x; applecoord->y = apple.y; *snakebody_length = SNAKEBODY_LENGTH; for (int k = 0; k < SNAKEBODY_LENGTH; k++) { snakebodycoords[k].x = snakebody[k].x; snakebodycoords[k].y = snakebody[k].y; } } pthread_mutex_unlock(&snakeGameData); } <file_sep>/snakeGame.h // snakeGame.h // Module to start/stop the "Snake" game thread and provide routines to retrieve game data. #ifndef _SNAKEGAME_H_ #define _SNAKEGAME_H_ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <pthread.h> #include <netdb.h> #include <string.h> #include <unistd.h> #include <time.h> #include "zen_joystick.h" #include "zen_accelerometer.h" #include "zen_buzzer.h" #include "ext_8x8led.h" #include "zen_segdisplay.h" //------- Enums and definitions -------------------- typedef struct { int x; int y; } snakegame_coords; //------- function prototypes ---------------------- // Start the game thread // void snakeGame_start(void); // Stop the game thread // void snakeGame_stop(void); // Get game data // *snakebody_length = length of snake's body (number of pixels) // *snakebodycoords = pointer to array of coordinates for snake's body // *applecoords = pointer to coordinates of apple // *apples_eaten = number of apples eaten by snake // void snakeGame_GetData (int *snakebody_length, snakegame_coords *snakebodycoords, snakegame_coords *applecoord, int *apples_eaten); #endif <file_sep>/Makefile # Makefile for building embedded application. OUTFILE1 = miniGamesConsole OUTDIR = $(HOME)/cmpt433/public/myApps CROSS_COMPILE = arm-linux-gnueabihf- CC_C = $(CROSS_COMPILE)gcc CFLAGS = -Wall -g -std=c99 -D _POSIX_C_SOURCE=200809L -Werror # Default is "make all" all: miniGamesConsole node done miniGamesConsole: @echo "Building miniGamesConsole" @echo " " $(CC_C) $(CFLAGS) miniGamesConsole.c snakeGame.c balanceGame.c catchGame.c simonGame.c floppyBirbGame.c bbg_led.c udpServer1.c ext_8x8led.c ext_photoresistor.c ext_buttons.c zen_buzzer.c zen_joystick.c zen_accelerometer.c zen_segdisplay.c zen_potentiometer.c -pthread -o $(OUTDIR)/$(OUTFILE1) @echo " " node: mkdir -p $(OUTDIR)/miniGamesConsole-server-copy/ cp -R server1/* $(OUTDIR)/miniGamesConsole-server-copy/ cd $(OUTDIR)/miniGamesConsole-server-copy/ && npm install done: @echo "Finished building application." @echo " " @echo "Application location:" ls -l $(OUTDIR)/$(OUTFILE1) @echo " " clean: ifeq (,$(wildcard $(OUTDIR)/$(OUTFILE1))) else rm $(OUTDIR)/$(OUTFILE1) endif help: @echo "Build sorter program for BeagleBone" @echo "Targets include all, app, and clean." <file_sep>/ext_buttons.c // By <NAME> #include "ext_buttons.h" //------------ variables and definitions ----------------------- #define GPIO_FILEPATH_PREFIX "/sys/class/gpio/gpio" struct PushButtonInfo { const char *namestr; const int portnum; }; static const struct PushButtonInfo pushbuttons[] = { {"SELECT", 66}, // {"SELECT", 111}, {"ENTER_EXIT", 67} // {"ENTER_EXIT", 112} }; static _Bool previous_state[PUSH_MAXBUTTONS]; //------------ functions --------------------------------------- //***** static functions ****************************** static void assert_extPushButton_OK (enum extPushButton button) { assert((button >= PUSHBUTTON_SELECT) && (button < PUSH_MAXBUTTONS)); } //***** public functions ****************************** // Initialize external push-buttons. void extPushButtonInit () { char buffstr[128]; FILE *GPIOFile; struct timespec reqDelay; reqDelay.tv_sec = 0; reqDelay.tv_nsec = 300000000; // 300ms // Export GPIO pins for (int k = 0; k < PUSH_MAXBUTTONS; k++) { GPIOFile = fopen("/sys/class/gpio/export", "w"); if (GPIOFile == NULL) { printf("ERROR! Cannot open /sys/class/gpio/export for writing!\n"); exit(1); } fprintf(GPIOFile, "%d", pushbuttons[k].portnum); fclose(GPIOFile); } nanosleep(&reqDelay, (struct timespec *) NULL); // Configure GPIO pins as inputs for (int k = 0; k < PUSH_MAXBUTTONS; k++) { sprintf(buffstr, "/sys/class/gpio/gpio%d/direction", pushbuttons[k].portnum); GPIOFile = fopen(buffstr, "w"); if (GPIOFile == NULL) { printf("ERROR! Cannot open %s for writing!\n", buffstr); exit(1); } fprintf(GPIOFile, "in"); fclose(GPIOFile); } } // Check if a button is pushed. // Return value: true = pressed, false = not pressed, or unsuccessful file I/O. // // This function assumes that the GPIO pins have been // programmed such that 0 = pushed, 1 = not pushed. // _Bool extPushButtonPushed (enum extPushButton button) { char filepath[128]; // Parameters range checking assert_extPushButton_OK(button); // Compose filename sprintf(filepath, "%s%02d/value", GPIO_FILEPATH_PREFIX, pushbuttons[button].portnum); FILE *GPIOPortFile = fopen(filepath, "r"); if (GPIOPortFile == NULL) { printf("ERROR OPENING %s.\r\n", filepath); return false; } // Read status character fgets(filepath, 128, GPIOPortFile); // Make sure to close file fclose(GPIOPortFile); // Check value character if (filepath[0] == '0') return true; else return false; } // Check if a button is pressed. // Return value: true = pressed, false = not pressed // _Bool extPushButtonPressed (enum extPushButton button) { _Bool retval, currval; currval = extPushButtonPushed(button); if (!previous_state[button] && currval) { // button pressed retval = true; } else retval = false; previous_state[button] = currval; return retval; } // Check if a button is released. // Return value: true = released, false = not released // _Bool extPushButtonReleased (enum extPushButton button) { _Bool retval, currval; currval = extPushButtonPushed(button); if (previous_state[button] && !currval) { // button released retval = true; } else retval = false; previous_state[button] = currval; return retval; } // Get name string of button const char *extPushButtonName (enum extPushButton button) { return(pushbuttons[button].namestr); } <file_sep>/catchGame.c // catchGame.c // Module to start/stop the "Catch" game thread and provide routines to retrieve game data. #include "catchGame.h" //------------ variables and definitions ----------------------- static pthread_t catchGame_id; static pthread_mutex_t catchGameStat = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t catchGameData = PTHREAD_MUTEX_INITIALIZER; static int catches = 0; static int attempts = 0; static int currposx = 3; static int ballposx, ballposy; extern unsigned char font8x8[]; //------------ functions --------------------------------------- //***** static functions ****************************** //------------------------------------------------------- // Draw catcher //------------------------------------------------------- static void drawCatcher(unsigned int xpos, unsigned char pixel) { extLED8x8DrawPixel(xpos, 7, pixel); extLED8x8DrawPixel(xpos-1, 6, pixel); extLED8x8DrawPixel(xpos-1, 7, pixel); extLED8x8DrawPixel(xpos+1, 6, pixel); extLED8x8DrawPixel(xpos+1, 7, pixel); } //------------------------------------------------------- // "Catch the falling ball" game. //------------------------------------------------------- static void *catchGameThread() { enum zenJoystickButton button; struct timespec reqDelay; unsigned int sampcnt = 0; unsigned int ballslowness = 6; unsigned int dropcount = 0; catches = 0; attempts = 0; currposx = 3; // Draw catcher extLED8x8FillPixel(0); drawCatcher(currposx, 1); extLED8x8DisplayUpdate(); // Initialize catch score on seg display zenSegDisplayUpdateNum(catches); reqDelay.tv_sec = 0; reqDelay.tv_nsec = 100000000; // 100ms sampling rate // Draw ball ballposx = (rand() % 6) + 1; ballposy = 0; extLED8x8DrawPixel(ballposx, ballposy, 1); while (1) { // Sample all joystick buttons for (button = JOYSTICK_UP; button < JOYSTICK_MAXBUTTONS; button++) { if (zenJoystickButtonPushed (button)) { break; } } // Process ball dropping if (++sampcnt == ballslowness) { sampcnt = 0; pthread_mutex_lock(&catchGameData); { if ((ballposy != 6) || ((ballposy == 6) && (ballposx != (currposx-1)) && (ballposx != (currposx+1)))) extLED8x8DrawPixel(ballposx, ballposy, 0); if (ballposy == 6) { if (ballposx == currposx) { zenBuzzerBeep(440, 100); catches++; zenSegDisplayUpdateNum(catches); // Update score to seg display } else { zenBuzzerBeep(110, 300); } attempts++; printf("Attempts=%d, Catches=%d\n", attempts, catches); ballposx = (rand() % 6) + 1; ballposy = 0; // Speed up dropping if (++dropcount == 4) { dropcount = 0; if (ballslowness > 2) ballslowness--; } } else { ballposy++; } } pthread_mutex_unlock(&catchGameData); extLED8x8DrawPixel(ballposx, ballposy, 1); extLED8x8DisplayUpdate(); } // Process catcher if (button < JOYSTICK_MAXBUTTONS) { if (button == JOYSTICK_LEFT) { if (currposx > 1) { pthread_mutex_lock(&catchGameData); { drawCatcher(currposx--, 0); drawCatcher(currposx, 1); } pthread_mutex_unlock(&catchGameData); if ((ballposy == 6) && (ballposx == currposx)) extLED8x8DrawPixel(ballposx, ballposy, 1); extLED8x8DisplayUpdate(); } } else if (button == JOYSTICK_RIGHT) { if (currposx < 6) { pthread_mutex_lock(&catchGameData); { drawCatcher(currposx++, 0); drawCatcher(currposx, 1); } pthread_mutex_unlock(&catchGameData); if ((ballposy == 6) && (ballposx == currposx)) extLED8x8DrawPixel(ballposx, ballposy, 1); extLED8x8DisplayUpdate(); } } } // sampling delay nanosleep(&reqDelay, (struct timespec *) NULL); // Check for request to terminate thread int lockstat; lockstat = pthread_mutex_trylock(&catchGameStat); if (lockstat == 0) { // lock acquired (0) means terminate pthread_exit(0); } } pthread_exit(0); } //***** public functions ****************************** void catchGame_start (void) { printf("Starting game of 'Catch'\n"); // 3, 2, 1 count down extLED8x8CountDown321(font8x8); pthread_mutex_init(&catchGameStat, NULL); // Lock mutex used by thread to check for request to end the thread pthread_mutex_lock(&catchGameStat); // Start the thread pthread_create(&catchGame_id, NULL, &catchGameThread, NULL); } void catchGame_stop (void) { // Unlock mutex to let sorting thread know about request to finish pthread_mutex_unlock(&catchGameStat); printf("Stopping game of 'Catch'\n"); // Exit game logo extLED8x8ExitGame(font8x8); // Wait for thread to finish pthread_join(catchGame_id, NULL); } void catchGame_GetData(int *attempt, int *catch, int *ballx, int *bally, int *catchx) { pthread_mutex_lock(&catchGameData); { *attempt = attempts; *catch = catches; *ballx = ballposx; *bally = ballposy; *catchx = currposx; } pthread_mutex_unlock(&catchGameData); } <file_sep>/miniGamesConsole.c // miniGamesConsole.c // Main program for "Mini Games Console" project. // #include <stdio.h> #include <stdlib.h> #include <time.h> #include "bbg_led.h" #include "zen_joystick.h" #include "zen_buzzer.h" #include "zen_accelerometer.h" #include "zen_potentiometer.h" #include "zen_segdisplay.h" #include "ext_8x8led.h" #include "ext_buttons.h" #include "icons8x8.h" #include "font8x8.h" #include "udpServer1.h" #include "balanceGame.h" #include "catchGame.h" #include "simonGame.h" #include "snakeGame.h" #include "floppyBirbGame.h" #define MAX_GAMES 5 int anim_count = 0; int sample_count = 0; _Bool game_running = false; int game_selection = 0; unsigned char led_brightness; char *(gamename[]) = { "SIMON", "CATCH", "BALANCE", "SNAKE", "FLOPPY BIRB" }; int main(int argc, char **argv) { int potvalue; zenSegDisplayInit(); zenSegDisplayStart(); zenAccelerometerInit(); zenJoystickInit(); zenBuzzerInit(); extPushButtonInit(); struct timespec reqDelay; reqDelay.tv_sec = 0; reqDelay.tv_nsec = 10000000; // Initialize 8x8 LED display if (extLED8x8Init() == false) { printf("ERROR! extLED8x8Init() returned false!\n"); return 1; } // Turn on 8x8 LED display if (extLED8x8DisplayOn(HT16K33_BLINK_OFF) == false) { printf("ERROR! extLED8x8DisplayOn() returned false!\n"); return 1; } // Set the rotation of the 8x8 LED display extLED8x8SetDisplayRotation(DISPLAY_ROTATE0); // Start UDP listener UDPServer_startListening(); // Main game loop while (1) { if (game_running == true) { // A game is running // Check for exiting game if (extPushButtonPressed(PUSHBUTTON_ENTER_EXIT) == true) { switch(game_selection) { case 0: // Simon game simonGame_stop(); break; case 1: // Catch game catchGame_stop(); break; case 2: // Balance game balanceGame_stop(); break; case 3: // Snake game snakeGame_stop(); break; case 4: // Floppy Birb game floppyBirbGame_stop(); break; } game_running = false; } } else { // Game is not running // Display game icon(s) switch(game_selection) { case 0: // Simon game zenSegDisplayUpdateNum(0); // Game #0 extLED8x8FillPixel(0); if (anim_count < 3) extLED8x8LoadImage(&(icons8x8[RIGHT_ARROW_ICON+(anim_count * 8)])); else extLED8x8LoadImage(&(icons8x8[RIGHT_ARROW_ICON+(3 * 8)])); extLED8x8DisplayUpdate(); break; case 1: // Catch game zenSegDisplayUpdateNum(1); // Game #1 extLED8x8FillPixel(0); extLED8x8DrawPixel(3, 6, 1); extLED8x8DrawPixel(5, 6, 1); extLED8x8DrawPixel(3, 7, 1); extLED8x8DrawPixel(4, 7, 1); extLED8x8DrawPixel(5, 7, 1); if (anim_count < 4) extLED8x8DrawPixel(4, anim_count+2, 1); else extLED8x8DrawPixel(4, 6, 1); extLED8x8DisplayUpdate(); break; case 2: // Balance game zenSegDisplayUpdateNum(2); // Game #1 extLED8x8FillPixel(0); if (anim_count == 0) extLED8x8DrawPixel(3, 3, 1); else if (anim_count == 1) extLED8x8DrawPixel(4, 4, 1); else if (anim_count == 2) extLED8x8DrawPixel(5, 4, 1); else if (anim_count == 3) extLED8x8DrawPixel(5, 3, 1); else if (anim_count == 4) extLED8x8DrawPixel(4, 3, 1); else extLED8x8DrawPixel(3, 4, 1); extLED8x8DisplayUpdate(); break; case 3: // Snake game zenSegDisplayUpdateNum(3); // Game #3 extLED8x8FillPixel(0); if (anim_count == 0) { extLED8x8DrawPixel(3, 3, 1); extLED8x8DrawPixel(4, 3, 1); extLED8x8DrawPixel(5, 3, 1); extLED8x8DrawPixel(6, 3, 1); } else if (anim_count == 1) { extLED8x8DrawPixel(5, 3, 1); extLED8x8DrawPixel(6, 3, 1); extLED8x8DrawPixel(6, 4, 1); extLED8x8DrawPixel(6, 5, 1); } else if (anim_count == 2) { extLED8x8DrawPixel(6, 4, 1); extLED8x8DrawPixel(6, 5, 1); extLED8x8DrawPixel(5, 5, 1); extLED8x8DrawPixel(4, 5, 1); } else if (anim_count == 3) { extLED8x8DrawPixel(5, 5, 1); extLED8x8DrawPixel(4, 5, 1); extLED8x8DrawPixel(3, 5, 1); extLED8x8DrawPixel(3, 4, 1); } else if (anim_count == 4) { extLED8x8DrawPixel(3, 5, 1); extLED8x8DrawPixel(3, 4, 1); extLED8x8DrawPixel(3, 3, 1); extLED8x8DrawPixel(4, 3, 1); } else { extLED8x8DrawPixel(3, 4, 1); extLED8x8DrawPixel(3, 3, 1); extLED8x8DrawPixel(4, 3, 1); extLED8x8DrawPixel(5, 3, 1); } extLED8x8DisplayUpdate(); break; case 4: // Floppy Birb game zenSegDisplayUpdateNum(4); // Game #4 extLED8x8FillPixel(0); if (anim_count == 0) { extLED8x8DrawPixel(1, 4, 1); extLED8x8DrawPixel(2, 3, 1); } else if (anim_count == 1) { extLED8x8DrawPixel(2, 3, 1); extLED8x8DrawPixel(3, 3, 1); } else if (anim_count == 2) { extLED8x8DrawPixel(3, 3, 1); extLED8x8DrawPixel(4, 4, 1); } else if (anim_count == 3) { extLED8x8DrawPixel(4, 4, 1); extLED8x8DrawPixel(5, 3, 1); } else if (anim_count == 4) { extLED8x8DrawPixel(5, 3, 1); extLED8x8DrawPixel(6, 3, 1); } extLED8x8DisplayUpdate(); break; } // Increment animation count if (++sample_count == 25) { sample_count = 0; if (++anim_count == 6) anim_count = 0; } // Check if ENTER is pressed to run game if (extPushButtonPressed(PUSHBUTTON_ENTER_EXIT) == true) { game_running = true; switch(game_selection) { case 0: // Simon game simonGame_start(); break; case 1: // Catch game catchGame_start(); break; case 2: // Balance game balanceGame_start(); break; case 3: // Snake game snakeGame_start(); break; case 4: // Floppy Birb game floppyBirbGame_start(); break; } } // Read potentiometer and adjust 8x8 LED brightness potvalue = zenPotentiometerReadA2DValue(); led_brightness = (unsigned char) (potvalue>>8); if (extLED8x8DisplayBrightness(led_brightness) == false) { printf("ERROR! extLED8x8DisplayBrightness() returned false!\n"); return 1; } // Check if SELECTION is pressed to cycle through game selection if (extPushButtonPressed(PUSHBUTTON_SELECT) == true) { if (++game_selection == MAX_GAMES) game_selection = 0; printf("'%s' game selected\n", gamename[game_selection]); } } nanosleep(&reqDelay, (struct timespec *) NULL); } return 0; } <file_sep>/zen_buzzer.h // zen_buzzer.h // Routines/definitions for Zen Cape's buzzer #ifndef ZEN_BUZZER_H #define ZEN_BUZZER_H #include <stdbool.h> #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <time.h> //------- Enums and definitions -------------------- //------- function prototypes ---------------------- // Initialize Zen buzzer. void zenBuzzerInit (); // Must be called before using functions // Turn on the buzzer with a specific frequency (Hz). // void zenBuzzerOn(long freq); // Turn off the buzzer. // void zenBuzzerOff(); // Turn on the buzzer with a specific frequency (Hz) and duration (ms). // void zenBuzzerBeep(long freq, long duration); #endif <file_sep>/server/public/javascripts/game_ui.js "use strict"; // Client-side interactions with the browser. // Web sockets: automatically establish a socket with the server var socket = io.connect(); // Make connection to server when web page is fully loaded. $(document).ready(function() { // Make the text-entry box have keyboard focus. $('#send-command').focus(); // Allow sending the form (pressing enter). $('#send-form').submit(function() { readUserInput(); // Return false to show we have handleded it. return false; }); $('#brightnessUp').click(function() { AddBrightness(); return false; }); $('#brightnessDown').click(function() { MinusBrightness(); return false; }); $('#new-game').click(function() { $('#messages').html(''); return false; }); $('#reset').click(function() { $('#status').html(''); return false; }); // Handle data coming back from the server socket.on('endOutput', function(result) { $('#messages').append(divMessage(result)); $('#status').append(listMessage(result)); }); socket.on('getBrightness', function(result) { $('#messages').append(divMessage('Brightness : ' + result)); $('#brightness').val(result); }); socket.on('getCurrentScore', function(result) { $('#score').val(result); }); socket.on('daError', function(result) { var msg = divMessage('SERVER ERROR: ' + result); $('#messages').append(msg); }); }); function readUserInput() { // Get the user's input from the browser. var message = $('#send-command').val(); // Display the command in the message list. $('#messages').append(divMessage(message)); // Process the command var systemMessage = processCommand(message); if (systemMessage != false) { $('#messages').append(divMessage(systemMessage)); } // Scroll window. $('#messages').scrollTop($('#messages').prop('scrollHeight')); // Clear the user's command (ready for next command). $('#send-command').val(''); } function AddBrightness() { var value = $('#brightness').val(); var temp = Number(value); if (temp == NaN) { return; } value = temp + 1; if (value > 100) { value = 100; } $('#brightness').val(value); } function MinusBrightness() { var value = $('#brightness').val(); var temp = Number(value); if (temp == NaN) { return; } value = temp - 1; if (value < 0) { value = 0; } $('#brightness').val(value); } function processCommand(command) { var words = command.split(' '); var returnMessage = false; var scoreWord = Number(words[0]); if (words[0] == 'over') { var score = Number(words[1]); var today = new Date(); var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate(); var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds(); var dateTime = date+' '+time; // var name = words[2]; // if (name == null || name == '') { // return returnMessage; // } // console.log("Gets here.\n"); var name = window.prompt("Please enter your name", "<NAME>"); if (name == null || name == "") { return returnMessage; } returnMessage = name + ' ' + score + ' ' + dateTime; socket.emit('endRound', returnMessage); } else if (words[0] == 'brightness') { // console.log("Gets here.\n"); var value = Number(words[1]); if (value == NaN) { return returnMessage; } if (value > 100) { value = 100; } if (value < 0) { value = 0; } //console.log("Gets here.\n"); socket.emit('setBrightness', value); } else if (Number.isInteger(scoreWord)) { socket.emit('setCurrentScore', scoreWord); } else { returnMessage = 'Unrecognized command.' } return returnMessage; } //Wrap a string in a new <div> tag function divMessage(inString) { return $('<div></div>').text(inString); } function listMessage(inString) { return $('<li></li>').text(inString); } <file_sep>/zen_buzzer.c #include "zen_buzzer.h" //------------ variables and definitions ----------------------- //------------ functions --------------------------------------- //***** static functions ****************************** //***** public functions ****************************** // Initialize Zen buzzer. void zenBuzzerInit () { FILE *PWMFile; struct timespec reqDelay; reqDelay.tv_sec = 0; reqDelay.tv_nsec = 300000000; // 300ms // Export PWM channel 0 of PWMCHIP2 PWMFile = fopen("/sys/class/pwm/pwmchip0/export", "w"); if (PWMFile == NULL) { printf("ERROR! Cannot open /sys/class/pwm/pwmchip0/export for writing!\n"); exit(1); } fprintf(PWMFile, "0"); fclose(PWMFile); nanosleep(&reqDelay, (struct timespec *) NULL); // Turn buzzer on and off briefly zenBuzzerOn(10000); zenBuzzerOff(); } // Turn on the buzzer with a specific frequency (Hz). void zenBuzzerOn(long freq) { FILE *PWMFile; // Set the duty cycle to 0 first PWMFile = fopen("/sys/class/pwm/pwmchip0/pwm0/duty_cycle", "w"); if (PWMFile == NULL) { printf("ERROR! Cannot open /sys/class/pwm/pwmchip0/pwm0/duty_cycle for writing!\n"); exit(1); } fprintf(PWMFile, "0"); fclose(PWMFile); // Set the period long period; period = 1000000000; // ns/s period = (period + (freq>>1))/freq; PWMFile = fopen("/sys/class/pwm/pwmchip0/pwm0/period", "w"); if (PWMFile == NULL) { printf("ERROR! Cannot open /sys/class/pwm/pwmchip0/pwm0/period for writing!\n"); exit(1); } fprintf(PWMFile, "%ld", period); fclose(PWMFile); // Set the duty cycle (period/2) PWMFile = fopen("/sys/class/pwm/pwmchip0/pwm0/duty_cycle", "w"); if (PWMFile == NULL) { printf("ERROR! Cannot open /sys/class/pwm/pwmchip0/pwm0/duty_cycle for writing!\n"); exit(1); } fprintf(PWMFile, "%ld", period/2); fclose(PWMFile); // Turn on buzzer PWMFile = fopen("/sys/class/pwm/pwmchip0/pwm0/enable", "w"); if (PWMFile == NULL) { printf("ERROR! Cannot open /sys/class/pwm/pwmchip0/pwm0/enable for writing!\n"); exit(1); } fprintf(PWMFile, "1"); fclose(PWMFile); } // Turn on the buzzer with a specific frequency (Hz) and duration (ms). void zenBuzzerBeep(long freq, long duration) { FILE *PWMFile; // Set the duty cycle to 0 first PWMFile = fopen("/sys/class/pwm/pwmchip0/pwm0/duty_cycle", "w"); if (PWMFile == NULL) { printf("ERROR! Cannot open /sys/class/pwm/pwmchip0/pwm0/duty_cycle for writing!\n"); exit(1); } fprintf(PWMFile, "0"); fclose(PWMFile); // Set the period long period; period = 1000000000; // ns/s period = (period + (freq>>1))/freq; PWMFile = fopen("/sys/class/pwm/pwmchip0/pwm0/period", "w"); if (PWMFile == NULL) { printf("ERROR! Cannot open /sys/class/pwm/pwmchip0/pwm0/period for writing!\n"); exit(1); } fprintf(PWMFile, "%ld", period); fclose(PWMFile); // Set the duty cycle (period/2) PWMFile = fopen("/sys/class/pwm/pwmchip0/pwm0/duty_cycle", "w"); if (PWMFile == NULL) { printf("ERROR! Cannot open /sys/class/pwm/pwmchip0/pwm0/duty_cycle for writing!\n"); exit(1); } fprintf(PWMFile, "%ld", period/2); fclose(PWMFile); // Turn on buzzer PWMFile = fopen("/sys/class/pwm/pwmchip0/pwm0/enable", "w"); if (PWMFile == NULL) { printf("ERROR! Cannot open /sys/class/pwm/pwmchip0/pwm0/enable for writing!\n"); exit(1); } fprintf(PWMFile, "1"); fclose(PWMFile); // Delay for duration struct timespec reqDelay; if (duration >= 1000) { reqDelay.tv_sec = duration / 1000; reqDelay.tv_nsec = (duration % 1000) * 1000000; } else { reqDelay.tv_sec = 0; reqDelay.tv_nsec = duration * 1000000; } nanosleep(&reqDelay, (struct timespec *) NULL); // Turn off buzzer PWMFile = fopen("/sys/class/pwm/pwmchip0/pwm0/enable", "w"); if (PWMFile == NULL) { printf("ERROR! Cannot open /sys/class/pwm/pwmchip0/pwm0/enable for writing!\n"); exit(1); } fprintf(PWMFile, "0"); fclose(PWMFile); } // Turn off the buzzer. void zenBuzzerOff() { FILE *PWMFile; PWMFile = fopen("/sys/class/pwm/pwmchip0/pwm0/enable", "w"); if (PWMFile == NULL) { printf("ERROR! Cannot open /sys/class/pwm/pwmchip0/pwm0/enable for writing!\n"); exit(1); } fprintf(PWMFile, "0"); fclose(PWMFile); } <file_sep>/zen_accelerometer.h // zen_accelerometer.h // Routines/definitions for Zen Cape's accelerometer #ifndef ZEN_ACCELEROMETER_H #define ZEN_ACCELEROMETER_H #include <stdbool.h> #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <sys/ioctl.h> #include <linux/i2c.h> #include <linux/i2c-dev.h> //------- Enums and definitions -------------------- //------- function prototypes ---------------------- //***************************************************** // Initializes Zen Cape accelerometer. // Return value: true=success, false=fail //***************************************************** _Bool zenAccelerometerInit(); // Must be called before using functions //***************************************************** // Read X, Y, Z values from Zen Cape accelerometer. // Return value: true=success, false=fail //***************************************************** _Bool zenAccelerometerRead(int *xval, int *yval, int *zval); #endif <file_sep>/ext_photoresistor.c // By <NAME> #include "ext_photoresistor.h" //------------ variables and definitions ----------------------- #define A2D_FILE_VOLTAGE1 "/sys/bus/iio/devices/iio:device0/in_voltage1_raw" #define A2D_VOLTAGE_REF_V 1.8 #define A2D_MAX_READING 4095 //------------ functions --------------------------------------- //***** public functions ****************************** // Read A2D value of potentiometer. // Return value: 0 to 4095 (inclusive), or <0 if error occurred. int extPhotoresistorReadA2DValue () { // Open file FILE *A2DFile = fopen(A2D_FILE_VOLTAGE1, "r"); if (A2DFile == NULL) { printf("ERROR OPENING %s.\r\n", A2D_FILE_VOLTAGE1); return -1; } // Read value int a2dvalue; int itemsread = fscanf(A2DFile, "%d", &a2dvalue); if (itemsread <= 0) { printf("ERROR reading A2D value. Too few items read.\n"); return -1; } // Make sure to close file fclose(A2DFile); return a2dvalue; } // Read voltage of potentiometer. // Return value: 0 to 1.8V (inclusive), or <0 if error occurred. double extPhotoresistorReadVoltage () { // Read A2D value int a2dvalue = extPhotoresistorReadA2DValue(); if (a2dvalue < 0) // check for error return -1.0; // Calculate voltage return((((double) a2dvalue)/A2D_MAX_READING)*A2D_VOLTAGE_REF_V); } <file_sep>/udpServer1.c #include "udpServer1.h" #define MSG_MAX_LEN 1024 #define PORT 12345 //------------ variables and definitions ----------------------- static pthread_t udpServer_id; extern _Bool game_running; extern int game_selection; extern char *(gamename[]); extern unsigned char led_brightness; //------------ functions --------------------------------------- //***** static functions ****************************** //---------------------------------------------------- // Thread to continuously listen to UDP port and process // commands from client. //---------------------------------------------------- static char messageRx[MSG_MAX_LEN]; static void *udpServerThread () { // Address struct sockaddr_in sin; memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; // Connection may be from network sin.sin_addr.s_addr = htonl(INADDR_ANY); // Host to Network long sin.sin_port = htons(PORT); // Host to Network short // Create the socket for UDP int socketDescriptor = socket(PF_INET, SOCK_DGRAM, 0); // Bind the socket to the port (PORT) that we specify bind (socketDescriptor, (struct sockaddr*) &sin, sizeof(sin)); // Listening and processing loop while (1) { // Get the data (blocking) // Will change sin (the address) to be the address of the client. // Note: sin passes information in and out of call! struct sockaddr_in sinRemote; unsigned int sin_len = sizeof(sinRemote); int bytesRx = recvfrom(socketDescriptor, messageRx, MSG_MAX_LEN, 0, (struct sockaddr *) &sinRemote, &sin_len); // Make it null terminated (so string functions work): int terminateIdx = (bytesRx < MSG_MAX_LEN) ? bytesRx : MSG_MAX_LEN - 1; messageRx[terminateIdx] = 0; sin_len = sizeof(sinRemote); char *delimiters = " \r\n"; // for strtok() // Interpret commands char *token; token = strtok(messageRx, delimiters); char messageTx[20]; if (token != NULL) { unsigned char dispbuff[8]; // 'dispbuff' command if (strcmp(token, "dispbuff") == 0) { extLED8x8GetLocalBuffer(dispbuff); sprintf(messageTx, "%02X%02X%02X%02X%02X%02X%02X%02X", dispbuff[0], dispbuff[1], dispbuff[2], dispbuff[3], dispbuff[4], dispbuff[5], dispbuff[6], dispbuff[7] ); sendto( socketDescriptor, messageTx, strlen(messageTx), 0, (struct sockaddr *) &sinRemote, sin_len); } else if (strcmp(token, "gamerun") == 0) { if (game_running == true) sprintf(messageTx, "YES"); else sprintf(messageTx, "NO"); sendto( socketDescriptor, messageTx, strlen(messageTx), 0, (struct sockaddr *) &sinRemote, sin_len); } else if (strcmp(token, "gameselected") == 0) { sendto( socketDescriptor, gamename[game_selection], strlen(gamename[game_selection]), 0, (struct sockaddr *) &sinRemote, sin_len); } else if (strcmp(token, "ledbrightness") == 0) { sprintf(messageTx, "%02X", (led_brightness<<3) | 0x87); sendto( socketDescriptor, messageTx, strlen(messageTx), 0, (struct sockaddr *) &sinRemote, sin_len); } } } // Close close(socketDescriptor); pthread_exit(0); } //***** public functions ****************************** // Begin the background thread to read the potentiometer, void UDPServer_startListening (void) { // Start the thread pthread_create(&udpServer_id, NULL, &udpServerThread, NULL); } // End the background thread void UDPServer_stopListening (void) { // Wait for thread to finish pthread_join(udpServer_id, NULL); } <file_sep>/simonGame.c #include "simonGame.h" #include "icons8x8.h" //------------ variables and definitions ----------------------- static pthread_t simonGame_id; static pthread_mutex_t simonGameStat = PTHREAD_MUTEX_INITIALIZER; extern unsigned char font8x8[]; //------------ functions --------------------------------------- //***** static functions ****************************** //------------------------------------------------------- // // Check for request to terminate thread // Return Value: void //------------------------------------------------------- static void checkTermination() { int lockstat; lockstat = pthread_mutex_trylock(&simonGameStat); if (lockstat == 0) { // lock acquired (0) means terminate pthread_exit(0); } } //------------------------------------------------------- // Display current game generated buffer directions // Return Value: void //------------------------------------------------------- static void displayBuffer(int buff[], int curr_index) { struct timespec reqDelay; reqDelay.tv_sec = 1; reqDelay.tv_nsec = 0; // sampling rate for (int i = 0; i <= curr_index ; i++) { if (buff[i] == 0) { extLED8x8LoadImage(&icons8x8[UP_ARROW_ICON]); } else if (buff[i] == 1){ extLED8x8LoadImage(&icons8x8[DOWN_ARROW_ICON]); } else if (buff[i] == 2){ extLED8x8LoadImage(&icons8x8[LEFT_ARROW_ICON]); } else if (buff[i] == 3) { extLED8x8LoadImage(&icons8x8[RIGHT_ARROW_ICON]); } extLED8x8DisplayUpdate(); zenBuzzerBeep(440, 100); nanosleep(&reqDelay, (struct timespec *) NULL); checkTermination(); } } //------------------------------------------------------- // Randomly display an arrow direction // Return Value: JOYSTICK direction value //------------------------------------------------------- static int newDirection() { int x = rand() % 4; zenBuzzerBeep(440, 100); switch (x) { case 0: return JOYSTICK_UP; case 1: return JOYSTICK_DOWN; case 2: return JOYSTICK_LEFT; case 3: return JOYSTICK_RIGHT; } return -1; } //------------------------------------------------------- // Get user's joystick input // Return Value: user JOYSTICK direction value //------------------------------------------------------- static int getInput() { enum zenJoystickButton button; // Sample all joystick buttons while(1) { for (button = JOYSTICK_UP; button < JOYSTICK_MAXBUTTONS; button++) { if (zenJoystickButtonPressed(button)) { if (button == 0) { extLED8x8LoadImage(&icons8x8[UP_ARROW_ICON]); } else if (button == 1){ extLED8x8LoadImage(&icons8x8[DOWN_ARROW_ICON]); } else if (button == 2){ extLED8x8LoadImage(&icons8x8[LEFT_ARROW_ICON]); } else if (button == 3) { extLED8x8LoadImage(&icons8x8[RIGHT_ARROW_ICON]); } extLED8x8DisplayUpdate(); return button; } } checkTermination(); } return -1; } //------------------------------------------------------- // "Simon Says" game. //------------------------------------------------------- static void *simonGameThread() { enum zenJoystickButton buttonPressed; enum zenJoystickButton buttonNext; struct timespec reqDelay; reqDelay.tv_sec = 1; reqDelay.tv_nsec = 0; // sampling rate int maxLevel = 10001; int index = 0; int gameBuffer[maxLevel]; // Initialize user score to seg display zenSegDisplayUpdateNum(index); // Init game buffer for (int i = 0; i < maxLevel; i++) { gameBuffer[i] = -1; } while(1) { // Add new random arrow to game buffer buttonNext = newDirection(); if (buttonNext == -1) { printf("ERROR: Invalid new joystick direction.\n"); pthread_exit(0); } gameBuffer[index] = buttonNext; // Show current buffer directions displayBuffer(gameBuffer, index); // Add user input to user buffer _Bool wrong = false; for (int i = 0; i <= index ; i++) { buttonPressed = getInput(); if (buttonPressed == -1) { printf("ERROR: Invalid user joystick direction.\n"); pthread_exit(0); } // Check and update score if (buttonPressed == gameBuffer[i]) { zenBuzzerBeep(440, 100); printf("Correct!\n"); } else { // User input wrong, reset game buffer extLED8x8LoadImage(&(icons8x8[40])); extLED8x8DisplayUpdate(); zenBuzzerBeep(110, 300); zenBuzzerBeep(110, 300); zenBuzzerBeep(110, 300); zenBuzzerBeep(110, 300); zenBuzzerBeep(110, 300); printf("Incorrect! Reset to level 1.\n"); for (int i = 0; i < maxLevel; i++) { gameBuffer[i] = -1; } index = 0; wrong = true; zenSegDisplayUpdateNum(index); // Update score to seg display break; } checkTermination(); } if (!wrong) { // All user input correct extLED8x8LoadImage(&(icons8x8[0])); extLED8x8DisplayUpdate(); zenBuzzerBeep(440, 100); zenBuzzerBeep(440, 100); zenBuzzerBeep(440, 100); zenBuzzerBeep(440, 100); index++; printf("All correct! Level: %d passed!\n", index); zenSegDisplayUpdateNum(index); // Update score to seg display } // sampling delay nanosleep(&reqDelay, (struct timespec *) NULL); checkTermination(); } pthread_exit(0); } //***** public functions ****************************** void simonGame_start(void) { printf("Starting game of 'Simon'\n"); // Start seg display //zenSegDisplayStart(); // 3, 2, 1 count down extLED8x8CountDown321(font8x8); pthread_mutex_init(&simonGameStat, NULL); // Lock mutex used by thread to check for request to end the thread pthread_mutex_lock(&simonGameStat); // Start the thread pthread_create(&simonGame_id, NULL, &simonGameThread, NULL); } void simonGame_stop(void) { // Unlock mutex to let sorting thread know about request to finish pthread_mutex_unlock(&simonGameStat); // Stop seg display //zenSegDisplayStop(); printf("Stopping game of 'Simon'\n"); // Exit game logo extLED8x8ExitGame(font8x8); // Wait for thread to finish pthread_join(simonGame_id, NULL); } <file_sep>/ext_8x8led.h // ext_8x8led.h // Routines/definitions for external 8x8 LED display #ifndef EXT_8X8LED_H #define EXT_8X8LED_H #include <stdbool.h> #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <time.h> #include <fcntl.h> #include <unistd.h> #include <sys/ioctl.h> #include <linux/i2c.h> #include <linux/i2c-dev.h> //------- Enums and definitions -------------------- #define HT16K33_CMD_DISPRAM 0x00 #define HT16K33_CMD_SYSSETUP 0x20 #define HT16K33_CMD_DISPSETUP 0x80 #define HT16K33_CMD_BRIGHTNESS 0xE0 enum ht16k33_blink { HT16K33_BLINK_OFF = 0, HT16K33_BLINK_2HZ, HT16K33_BLINK_1HZ, HT16K33_BLINK_0_5HZ }; enum display_rotation { DISPLAY_ROTATE0 = 0, DISPLAY_ROTATE90, DISPLAY_ROTATE180, DISPLAY_ROTATE270 }; enum scroll_direction { SCROLL_UP = 0, SCROLL_DOWN, SCROLL_LEFT, SCROLL_RIGHT }; //------- function prototypes ---------------------- // Display routines //***************************************************** // Initializes the 8x8 LED matrix // Return value: true=success, false=fail //***************************************************** _Bool extLED8x8Init(); //***************************************************** // Updates the 8x8 LED matrix display RAM (pixel) data // Return value: true=success, false=fail //***************************************************** _Bool extLED8x8DisplayUpdate(); //***************************************************** // Turn off the 8x8 LED matrix. // Return value: true=success, false=fail //***************************************************** _Bool extLED8x8DisplayOff(); //***************************************************** // Turn on the 8x8 LED matrix. // Parameter "blinktype" specifies the blinking type. // Return value: true=success, false=fail //***************************************************** _Bool extLED8x8DisplayOn(enum ht16k33_blink blinktype); //***************************************************** // Set brightness level of 8x8 LED matrix. // Parameter "brightness" specifies the brightness level (0 to 15). // Return value: true=success, false=fail //***************************************************** _Bool extLED8x8DisplayBrightness(unsigned char brightness); // Drawing routines //***************************************************** // Set rotation of 8x8 display. 0, 90, 180, or 270 clockwise. //***************************************************** void extLED8x8SetDisplayRotation(enum display_rotation rotval); //***************************************************** // Fill local buffer with pixel value. //***************************************************** void extLED8x8FillPixel(unsigned char pixelval); //***************************************************** // Draw a pixel into the local buffer. // Top, left corner pixel coordinate is (0,0). // Bottom, right corner pixel coordinate is (7,7). //***************************************************** void extLED8x8DrawPixel(unsigned int x, unsigned int y, unsigned char pixelval); //***************************************************** // Load an 8x8 image into local buffer. //***************************************************** void extLED8x8LoadImage(unsigned char *img); // img is pointer to 8-byte unsigned char array //***************************************************** // Scroll 7-bit ASCII text one character at a time through the 8x8 matrix // txtstr: text string to display // fontset: 128-character 8x8 font set // scrollmsdelay: pixel shift delay in milliseconds // scrolldir: scroll direction //***************************************************** void extLED8x8ScrollText(char *txtstr, unsigned char *fontset, int scrollmsdelay, enum scroll_direction scrolldir); //***************************************************** // Countdown 3,2,1 //***************************************************** void extLED8x8CountDown321(unsigned char *font); //***************************************************** // LED logo for exiting a game //***************************************************** void extLED8x8ExitGame(unsigned char *font); //***************************************************** // Get local display buffer data //***************************************************** void extLED8x8GetLocalBuffer(unsigned char *font); #endif <file_sep>/zen_joystick.h // zen_joystick.h // Routines/definitions for Zen Cape's joystick #ifndef ZEN_JOYSTICK_H #define ZEN_JOYSTICK_H #include <stdbool.h> #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <time.h> //------- Enums and definitions -------------------- // Joystick buttons enum zenJoystickButton { JOYSTICK_UP = 0, JOYSTICK_DOWN, JOYSTICK_LEFT, JOYSTICK_RIGHT, JOYSTICK_ENTER, JOYSTICK_MAXBUTTONS }; //------- function prototypes ---------------------- // Initialize Zen joystick buttons. void zenJoystickInit (); // Must be called before using functions // Check if a button is pushed. // Return value: true = pushed, false = not pushed, or unsuccessful file I/O. // _Bool zenJoystickButtonPushed (enum zenJoystickButton button); // Check if a button is pressed ("not pushed" to "pushed"). // Return value: true = pressed, false = not pressed, or unsuccessful file I/O. // _Bool zenJoystickButtonPressed (enum zenJoystickButton button); // Check if a button is released ("pushed" to "not pushed"). // Return value: true = released, false = not released, or unsuccessful file I/O. // _Bool zenJoystickButtonReleased (enum zenJoystickButton button); // Get name string of button const char *zenJoystickButtonName (enum zenJoystickButton button); #endif <file_sep>/floppyBirbGame.c // floppyBirbGame.c // Module to start/stop the new game thread and provide routines to retrieve game data. #include "floppyBirbGame.h" //------------ variables and definitions ----------------------- #define BIRDBODY_LENGTH 2 #define N_WALLS 4 #define INIT_WALL_x 3 // The initial walls will be generated starting from this x-pos #define MAX_WALL_HEIGHT 3 #define SPACE_BETWEEN_WALLS 1 #define WALL_GAP 5 #define MAX_WIDTH 7 #define MIN_WIDTH 0 #define MAX_HEIGHT 0 #define MIN_HEIGHT 7 static pthread_t floppyBirbGame_id; static pthread_mutex_t floppyBirbGameStat = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t floppyBirbGameData = PTHREAD_MUTEX_INITIALIZER; static birdgame_coords birdbody[BIRDBODY_LENGTH]; // coordinates of bird's body (pixels) static birdgame_coords wall[N_WALLS]; // coordinates of walls to fly through static _Bool gameStopped = false; static _Bool hovering = false; static _Bool bird_in_motion = false; static _Bool detected_collision = false; static int points = 0; static int total_score = 0; // static enum zenJoystickButton current_direction; extern unsigned char font8x8[]; //------------ functions --------------------------------------- //***** static functions ****************************** static void drawBirdBody() { for (int k = 0; k < BIRDBODY_LENGTH; k++) extLED8x8DrawPixel(birdbody[k].x, birdbody[k].y, 1); } static void initBirdBody() { pthread_mutex_lock(&floppyBirbGameData); { // head birdbody[0].x = 2; birdbody[0].y = 3; // tail birdbody[1].x = 1; birdbody[1].y = 4; } pthread_mutex_unlock(&floppyBirbGameData); } static void flyUp() { // printf("Called flyUp()\n"); pthread_mutex_lock(&floppyBirbGameData); { // Check that we don't go out of bounds if (birdbody[0].y > MAX_HEIGHT) { // head birdbody[0].y--; // tail birdbody[1].y = birdbody[0].y + 1; // printf("flyUp()\n"); } } pthread_mutex_unlock(&floppyBirbGameData); } static void fallDown() { // printf("Called flyDown()\n"); pthread_mutex_lock(&floppyBirbGameData); { // Check that we don't go out of bounds if (birdbody[0].y < MIN_HEIGHT) { // head birdbody[0].y++; // tail birdbody[1].y = birdbody[0].y - 1; // printf("flyDown()\n"); } } pthread_mutex_unlock(&floppyBirbGameData); } static void hover() { pthread_mutex_lock(&floppyBirbGameData); { birdbody[1].y = birdbody[0].y; } pthread_mutex_unlock(&floppyBirbGameData); } static void initWalls() { pthread_mutex_lock(&floppyBirbGameData); { for (int k = 0; k < N_WALLS; k++) { wall[k].x = INIT_WALL_x + (k * 2); wall[k].y = rand() % MAX_WALL_HEIGHT; } } pthread_mutex_unlock(&floppyBirbGameData); } static void drawWalls() { for (int k = 0; k < N_WALLS; k++) { // Top half of wall for (int j = 0; j <= wall[k].y; j++) { extLED8x8DrawPixel(wall[k].x, wall[k].y - j, 1); } // Bottom half of wall for (int j = WALL_GAP + 1; j <= MIN_HEIGHT; j++) { extLED8x8DrawPixel(wall[k].x, wall[k].y + j, 1); } } } static void moveWalls() { int k; pthread_mutex_lock(&floppyBirbGameData); { // while(1) { for (k = 0; k < N_WALLS; k++) { wall[k].x--; if (wall[k].x < MIN_WIDTH) { wall[k].x = MAX_WIDTH; wall[k].y = rand() % MAX_WALL_HEIGHT; } } // } } pthread_mutex_unlock(&floppyBirbGameData); } static _Bool detect_collision() { _Bool collision = false; for (int i = 0; i < N_WALLS; i++) { for (int j = 0; j < BIRDBODY_LENGTH; j++) { if (((birdbody[j].x == wall[i].x) && (birdbody[j].y == wall[i].y)) || ((birdbody[j].x == wall[i].x) && (birdbody[j].y == wall[i].y + WALL_GAP + 1))) { collision = true; } } } return collision; } //------------------------------------------------------- // New game. //------------------------------------------------------- static void *floppyBirbGameThread() { struct timespec reqDelay; enum zenJoystickButton button; int samplecnt; points = 0; total_score = 0; gameStopped = false; bird_in_motion = false; // Initialize bird's body and walls initBirdBody(); initWalls(); // Draw bird on the left side of matrix and walls on the right side extLED8x8FillPixel(0); drawBirdBody(); drawWalls(); extLED8x8DisplayUpdate(); // Initialize score on seg display zenSegDisplayUpdateNum(total_score); reqDelay.tv_sec = 0; reqDelay.tv_nsec = 100000000; // 100ms sampling rate while (1) { // Sample all joystick buttons for (button = JOYSTICK_UP; button < JOYSTICK_MAXBUTTONS; button++) { if (zenJoystickButtonPushed (button)) { break; } } if (gameStopped == false) { if (bird_in_motion == false) { if (button < JOYSTICK_MAXBUTTONS) { // If any joystick button is pressed, fly up one unit flyUp(); extLED8x8FillPixel(0); drawBirdBody(); extLED8x8DisplayUpdate(); bird_in_motion = true; samplecnt = 0; } } else { // Bird is in flight if (++samplecnt == 2) { samplecnt = 0; // Check for collision first detected_collision = detect_collision(); if (detected_collision) { zenBuzzerBeep(110, 300); extLED8x8FillPixel(0); extLED8x8ScrollText(" Game Over!X", font8x8, 25, SCROLL_LEFT); gameStopped = true; continue; } // If any joystick button is pressed, fly up one unit else if (button < JOYSTICK_MAXBUTTONS) { flyUp(); extLED8x8FillPixel(0); drawBirdBody(); hovering = true; } else { if (hovering) { // Intermediate state between flying up and falling hover(); extLED8x8FillPixel(0); drawBirdBody(); hovering = false; } else { fallDown(); extLED8x8FillPixel(0); drawBirdBody(); } } // Move walls one position to the left moveWalls(); drawWalls(); extLED8x8DisplayUpdate(); // Increase score and display points++; if ((points % 10 == 0) && (points > 0)) { total_score++; zenBuzzerBeep(440, 100); } zenSegDisplayUpdateNum(total_score); } } } // sampling delay nanosleep(&reqDelay, (struct timespec *) NULL); // Check for request to terminate thread int lockstat; lockstat = pthread_mutex_trylock(&floppyBirbGameStat); if (lockstat == 0) { // lock acquired (0) means terminate pthread_exit(0); } } pthread_exit(0); } //***** public functions ****************************** void floppyBirbGame_start (void) { printf("Starting game of 'Floppy Birb'\n"); // 3, 2, 1 count down extLED8x8CountDown321(font8x8); pthread_mutex_init(&floppyBirbGameStat, NULL); // Lock mutex used by thread to check for request to end the thread pthread_mutex_lock(&floppyBirbGameStat); // Start the thread pthread_create(&floppyBirbGame_id, NULL, &floppyBirbGameThread, NULL); } void floppyBirbGame_stop (void) { // Unlock mutex to let sorting thread know about request to finish pthread_mutex_unlock(&floppyBirbGameStat); printf("Stopping game of 'Floppy Birb'\n"); // Exit game logo extLED8x8ExitGame(font8x8); // Wait for thread to finish pthread_join(floppyBirbGame_id, NULL); } void floppyBirbGame_GetData ( int *birdbody_length, birdgame_coords *birdbodycoords, int *score ) { pthread_mutex_lock(&floppyBirbGameData); { *birdbody_length = BIRDBODY_LENGTH; for (int i = 0; i < BIRDBODY_LENGTH; i++) { birdbodycoords[i].x = birdbody[i].x; birdbodycoords[i].y = birdbody[i].y; } *score = total_score; } pthread_mutex_unlock(&floppyBirbGameData); } <file_sep>/server1/lib/minigames_server.js "use strict"; /* * Relay commands and responses between web client and miniGamesConsole program */ // ---- Commands received from web client ---------- // 'dispbuff' = get 8x8 display buffer // 'ledbrightness' = get "LED brightness" status // 'gamerun' = get "game running" status // 'gameselected' = get "game selected" status // ------------------------------------------------- // ---- Commands/Responses sent to web client ------ // 'dispbuff' = 8-byte response of requested 'dispbuff' command // 'ledbrightness' = 2-digit hex string // 'gamerun' = 'YES' or 'NO' response to 'gamerun' command // 'gameselected' = name of game selected // ------------------------------------------------- var fs = require('fs'); var socketio = require('socket.io'); var dgram = require('dgram'); var io; exports.listen = function(server) { io = socketio.listen(server); io.set('log level 1'); io.sockets.on('connection', function(socket) { handleCommand(socket); }); }; function handleCommand(socket) { // Handle 'dispbuff' command socket.on('dispbuff', function(dispbuffName) { relayminiGamesConsoleCommand(socket, 'dispbuff', 'none'); }); // Handle 'gamerun' command socket.on('gamerun', function(gamerunName) { relayminiGamesConsoleCommand(socket, 'gamerun', 'none'); }); // Handle 'gameselected' command socket.on('gameselected', function(gameselectedName) { relayminiGamesConsoleCommand(socket, 'gameselected', 'none'); }); // Handle 'ledbrightness' command socket.on('ledbrightness', function(ledbrightnessName) { relayminiGamesConsoleCommand(socket, 'ledbrightness', 'none'); }); }; // Function to relay command from web client to miniGamesConsole, // and response from miniGamesConsole back to web client. function relayminiGamesConsoleCommand(socket, cmd, parm) { // Info for connecting to the local process via UDP var PORT = 12345; var HOST = '127.0.0.1'; var buffer = new Buffer(cmd + ' ' + parm); var client = dgram.createSocket('udp4'); client.send(buffer, 0, buffer.length, PORT, HOST, function(err, bytes) { if (err) throw err; console.log('UDP message sent to ' + HOST +':'+ PORT); }); client.on('listening', function () { var address = client.address(); console.log('UDP Client: listening on ' + address.address + ":" + address.port); }); // Handle an incoming message over the UDP from the local application. client.on('message', function (message, remote) { console.log("UDP Client: message Rx" + remote.address + ':' + remote.port +' - ' + message); var reply = message.toString('utf8') socket.emit(cmd, reply); // Forward to web client client.close(); }); client.on("UDP Client: close", function() { console.log("closed"); }); client.on("UDP Client: error", function(err) { console.log("error: ",err); }); } <file_sep>/README.md // How to set up the BeagleBone Minigame Console 1. Go to the main directory to find our Makefile. 2. Type: $make 3. This will automatically compile and copy the binaries to the remote beaglebone folder 4. SSH into the beaglebone 5. Go to /mnt/remote/myApps 6. Run with: #sudo ./miniGamesConsole 7. To open our website, open another SSH beaglebone terminal 8. Go to directory /mnt/remote/myApps/miniGamesConsole-server-copy 9. Run server with: #nodejs server.js 10. Go to website at 192.168.7.2:8088 <file_sep>/bbg_led.h // bbg_led.h // Routines/definitions for BeagleBone Green's 4 LEDs #ifndef BBG_LED_H #define BBG_LED_H #include <stdio.h> #include <stdbool.h> //------- Enums and definitions -------------------- // LED selection enum bbgLED { BBG_LED0 = 0, BBG_LED1, BBG_LED2, BBG_LED3, MAX_BBG_LEDS }; // LED trigger mode enum bbgLEDTrigMode { NONE = 0, TIMER, HEARTBEAT }; // LED on/off value enum bbgLEDOffOn { BBG_LED_OFF = 0, BBG_LED_ON }; //------- function prototypes ---------------------- // Initialize an LED trigger mode. // Return value: true=successful, false=not successful _Bool bbgLED_trigmode(enum bbgLED led, enum bbgLEDTrigMode trigmode); // LED on/off // Return value: true=successful, false=not successful _Bool bbgLED_set(enum bbgLED led, enum bbgLEDOffOn ledoffon); // All LEDs on/off // Return value: true=successful, false=not successful _Bool bbgLED_setall(enum bbgLEDOffOn ledoffon); #endif <file_sep>/zen_potentiometer.h // zen_potentiometer.h // Routines/definitions for Zen Cape's potentiometer #ifndef ZEN_POTENTIOMETER_H #define ZEN_POTENTIOMETER_H #include <stdbool.h> #include <assert.h> #include <stdio.h> //------- function prototypes ---------------------- // Read A2D value of potentiometer. // Return value: 0 to 4095 (inclusive), or <0 if error occurred. int zenPotentiometerReadA2DValue(); // Read voltage of potentiometer. // Return value: 0 to 1.8V (inclusive), or <0 if error occurred. double zenPotentiometerReadVoltage(); #endif <file_sep>/zen_potentiometer.c #include "zen_potentiometer.h" //------------ variables and definitions ----------------------- #define A2D_FILE_VOLTAGE0 "/sys/bus/iio/devices/iio:device0/in_voltage0_raw" #define A2D_VOLTAGE_REF_V 1.8 #define A2D_MAX_READING 4095 //------------ functions --------------------------------------- //***** public functions ****************************** // Read A2D value of potentiometer. // Return value: 0 to 4095 (inclusive), or <0 if error occurred. int zenPotentiometerReadA2DValue () { // Open file FILE *A2DFile = fopen(A2D_FILE_VOLTAGE0, "r"); if (A2DFile == NULL) { printf("ERROR OPENING %s.\r\n", A2D_FILE_VOLTAGE0); return -1; } // Read value int a2dvalue; int itemsread = fscanf(A2DFile, "%d", &a2dvalue); if (itemsread <= 0) { printf("ERROR reading A2D value. Too few items read.\n"); return -1; } // Make sure to close file fclose(A2DFile); return a2dvalue; } // Read voltage of potentiometer. // Return value: 0 to 1.8V (inclusive), or <0 if error occurred. double zenPotentiometerReadVoltage () { // Read A2D value int a2dvalue = zenPotentiometerReadA2DValue(); if (a2dvalue < 0) // check for error return -1.0; // Calculate voltage return((((double) a2dvalue)/A2D_MAX_READING)*A2D_VOLTAGE_REF_V); } <file_sep>/server/lib/game_server.js var socketio = require('socket.io'); var io; exports.listen = function(server) { io = socketio.listen(server); io.set('log level 1'); io.sockets.on('connection', function(socket) { handleCommand(socket); }); }; function handleCommand(socket) { var errorTimer = setTimeout(function() { socket.emit("daError", "Oops: User too slow at sending first command."); }, 5000); socket.on('endRound', function(message) { socket.emit('endOutput', message); clearTimeout(errorTimer); }); socket.on('setBrightness', function(data){ socket.emit('getBrightness', data) }); socket.on('setCurrentScore', function(data){ socket.emit('getCurrentScore', data) }); }; <file_sep>/zen_segdisplay.c #include "zen_segdisplay.h" //------------ variables and definitions ----------------------- static char *gpio61_outpath = "/sys/class/gpio/gpio61/value"; // Enable for left digit static char *gpio44_outpath = "/sys/class/gpio/gpio44/value"; // Enable for right digit static int i2cFileDesc; // REG14 and REG15 pair of values for each digit struct segdispregs { unsigned char reg14; unsigned char reg15; }; static int leftDigitNum = 0; static int rightDigitNum = 0; static pthread_t zenDisplay_id; static pthread_mutex_t zenDisplay_mutex = PTHREAD_MUTEX_INITIALIZER; // Look-up table for REG14 and REG15 registers for values 0 to 9 // Bit 76543210 // Byte0 = CXDJKLME // Byte1 = FPGHNAB- // // AAAAAAAAA // F P G H B // F P G H B // NNNN JJJJ // E M L K C // E M L K C // DDDDDDDDD XX static struct segdispregs segdisp_lookup[] = { // Byte0 Byte1 {0xA1, 0x86}, // 0: C-D----E, F----AB- {0x80, 0x12}, // 1: C-------, ---H--B- {0x31, 0x0E}, // 2: --DJ---E, ----NAB- {0xB0, 0x06}, // 3: C-DJ----, -----AB- {0x90, 0x8A}, // 4: C--J----, F---N-B- {0xB0, 0x8C}, // 5: C-DJ----, F---NA-- {0xB1, 0x8C}, // 6: C-DJ---E, F---NA-- {0x02, 0x14}, // 7: ------M-, ---H-A-- {0xB1, 0x8E}, // 8: C-DJ---E, F---NAB- {0x90, 0x8E} // 9: C--J----, F---NAB- }; //------------ functions --------------------------------------- //***** static functions ****************************** static void assert_zenSegDigit_OK (enum zenSegDigit digit) { assert((digit >= SEGDIGIT_LEFT) && (digit <= SEGDIGIT_BOTH)); } static void assert_zenSegDigitValue_OK (int value) { assert((value >= 0) && (value <= 9)); } static unsigned int count(unsigned int i) { unsigned int ret = 1; while (i /= 10) ret++; return ret; } //***************************************************** // Turn on 15-segment digits // Return value: true=success, false=fail //***************************************************** static _Bool zenSegDisplayDigitOn(enum zenSegDigit digit) { FILE *GPIOFile; // Parameters range checking assert_zenSegDigit_OK(digit); if ((digit == SEGDIGIT_LEFT) || (digit == SEGDIGIT_BOTH)) { GPIOFile = fopen(gpio61_outpath, "w"); if (GPIOFile == NULL) { printf("ERROR OPENING %s.\n", gpio61_outpath); return false; } fprintf(GPIOFile, "1"); // Set GPIO_61 to 1 fclose(GPIOFile); } if ((digit == SEGDIGIT_RIGHT) || (digit == SEGDIGIT_BOTH)) { GPIOFile = fopen(gpio44_outpath, "w"); if (GPIOFile == NULL) { printf("ERROR OPENING %s.\n", gpio44_outpath); return false; } fprintf(GPIOFile, "1"); // Set GPIO_44 to 1 fclose(GPIOFile); } return true; } //***************************************************** // Turn off 15-segment digits // Return value: true=success, false=fail //***************************************************** static _Bool zenSegDisplayDigitOff(enum zenSegDigit digit) { FILE *GPIOFile; // Parameters range checking assert_zenSegDigit_OK(digit); if ((digit == SEGDIGIT_LEFT) || (digit == SEGDIGIT_BOTH)) { GPIOFile = fopen(gpio61_outpath, "w"); if (GPIOFile == NULL) { printf("ERROR OPENING %s.\n", gpio61_outpath); return false; } fprintf(GPIOFile, "0"); // Set GPIO_61 to 0 fclose(GPIOFile); } if ((digit == SEGDIGIT_RIGHT) || (digit == SEGDIGIT_BOTH)) { GPIOFile = fopen(gpio44_outpath, "w"); if (GPIOFile == NULL) { printf("ERROR OPENING %s.\n", gpio44_outpath); return false; } fprintf(GPIOFile, "0"); // Set GPIO_44 to 0 fclose(GPIOFile); } return true; } //***************************************************** // Display a numeric digit. // 0 <= num <= 9. // Return value: true=success, false=fail //***************************************************** static _Bool zenSegDisplayNumDigit(int num) { unsigned char buff[2]; // Parameters range checking assert_zenSegDigitValue_OK(num); // Open I2C driver i2cFileDesc = open("/dev/i2c-1", O_RDWR); if (i2cFileDesc < 0) { printf("I2C DRV: Unable to open bus for read/write (/dev/i2c-1)\n"); return false; } // Set slave address to 0x20 int result = ioctl(i2cFileDesc, I2C_SLAVE, 0x20); if (result < 0) { printf("Unable to set I2C device to slave address to 0x20.\n"); return false; } buff[0] = 0x14; buff[1] = segdisp_lookup[num].reg14; int res = write(i2cFileDesc, buff, 2); if (res != 2) { printf("ERROR! Unable to write i2c register\n"); return false; } buff[0] = 0x15; buff[1] = segdisp_lookup[num].reg15; res = write(i2cFileDesc, buff, 2); if (res != 2) { printf("ERROR! Unable to write i2c register\n"); return false; } close(i2cFileDesc); return true; } //***************************************************** // Thread which updates seg display. // Return value: None/NULL //***************************************************** static void *segDisplayThread() { struct timespec reqDelay; reqDelay.tv_sec = 0; reqDelay.tv_nsec = 5000000; while(1) { // Update Left Display zenSegDisplayDigitOff(SEGDIGIT_BOTH); pthread_mutex_lock(&zenDisplay_mutex); zenSegDisplayNumDigit(leftDigitNum); zenSegDisplayDigitOn(SEGDIGIT_LEFT); nanosleep(&reqDelay, (struct timespec *) NULL); zenSegDisplayDigitOff(SEGDIGIT_LEFT); // Update Right Display zenSegDisplayDigitOff(SEGDIGIT_BOTH); zenSegDisplayNumDigit(rightDigitNum); zenSegDisplayDigitOn(SEGDIGIT_RIGHT); nanosleep(&reqDelay, (struct timespec *) NULL); pthread_mutex_unlock(&zenDisplay_mutex); } return NULL; } //***** public functions ****************************** //***************************************************** // Initializes 2-digit x 15-segment LED display // Return value: true=success, false=fail //***************************************************** _Bool zenSegDisplayInit() { FILE *GPIOFile; struct timespec reqDelay; reqDelay.tv_sec = 0; reqDelay.tv_nsec = 300000000; // 300ms //---------------------------------------------------------------- // Export GPIO_44 and GPIO_61 //---------------------------------------------------------------- GPIOFile = fopen("/sys/class/gpio/export", "w"); if (GPIOFile == NULL) { printf("ERROR! Cannot open /sys/class/gpio/export for writing!\n"); exit(1); } fprintf(GPIOFile, "44"); fclose(GPIOFile); GPIOFile = fopen("/sys/class/gpio/export", "w"); if (GPIOFile == NULL) { printf("ERROR! Cannot open /sys/class/gpio/export for writing!\n"); exit(1); } fprintf(GPIOFile, "61"); fclose(GPIOFile); nanosleep(&reqDelay, (struct timespec *) NULL); //---------------------------------------------------------------- // Configure P8_26 (GPIO_61) and P8_12 (GPIO_44) pins as outputs // to turn on/off each 15-segment digit. Initialize as "off" (0). //---------------------------------------------------------------- // Configure GPIO_44 as output (enable for right digit) GPIOFile = fopen("/sys/class/gpio/gpio44/direction", "w"); if (GPIOFile == NULL) { printf("ERROR! Cannot open /sys/class/gpio/gpio44/direction for writing!\n"); exit(1); } fprintf(GPIOFile, "out"); // Configure GPIO_44 as output fclose(GPIOFile); // Configure GPIO_61 as output (enable for left digit) GPIOFile = fopen("/sys/class/gpio/gpio61/direction", "w"); if (GPIOFile == NULL) { printf("ERROR! Cannot open /sys/class/gpio/gpio64/direction for writing!\n"); exit(1); } fprintf(GPIOFile, "out"); // Configure GPIO_61 as output fclose(GPIOFile); // Set GPIO_61 output to 0 (turn off left digit) GPIOFile = fopen(gpio61_outpath, "w"); if (GPIOFile == NULL) { printf("ERROR OPENING %s.\n", gpio61_outpath); return false; } fprintf(GPIOFile, "0"); // Set GPIO_61 to 0 fclose(GPIOFile); // Set GPIO_44 output to 0 (turn off right digit) GPIOFile = fopen(gpio44_outpath, "w"); if (GPIOFile == NULL) { printf("ERROR OPENING %s.\n", gpio44_outpath); return false; } fprintf(GPIOFile, "0"); // Set GPIO_44 to 0 fclose(GPIOFile); //---------------------------------------------------------------- // Initialize I2C interface to control GPIO outputs for 2x15 segmented LED display //---------------------------------------------------------------- // Open I2C driver i2cFileDesc = open("/dev/i2c-1", O_RDWR); if (i2cFileDesc < 0) { printf("I2C DRV: Unable to open bus for read/write (/dev/i2c-1)\n"); return false; } // Set slave address to 0x20 int result = ioctl(i2cFileDesc, I2C_SLAVE, 0x20); if (result < 0) { printf("Unable to set I2C device to slave address to 0x20.\n"); return false; } // Set registers 0x00 and 0x01 to 0x00. unsigned char buff[2]; buff[0] = 0x00; buff[1] = 0x00; result = write(i2cFileDesc, buff, 2); if (result != 2) { printf("ERROR! Unable to write i2c register\n"); return false; } buff[0] = 0x01; result = write(i2cFileDesc, buff, 2); if (result != 2) { printf("ERROR! Unable to write i2c register\n"); return false; } close(i2cFileDesc); return true; // success } //***************************************************** // Converts new number to left and right digits // Return value: void //***************************************************** void zenSegDisplayUpdateNum(int newNum) { pthread_mutex_lock(&zenDisplay_mutex); // Make sure newNum between [0 - 99] // Put left digit in temp[0], right digit in temp[1] int temp[2]; if (newNum < 0) { temp[SEGDIGIT_LEFT] = 0; temp[SEGDIGIT_RIGHT] = 0; } else if ( newNum < 10) { temp[SEGDIGIT_LEFT] = 0; temp[SEGDIGIT_RIGHT] = newNum; } else if (newNum > 99) { temp[SEGDIGIT_LEFT] = 9; temp[SEGDIGIT_RIGHT] = 9; } else { unsigned int digit = count(newNum); while (digit--) { temp[digit] = newNum % 10; newNum /= 10; } } // Update left and right , segDisplayThread will automatically read them leftDigitNum = temp[SEGDIGIT_LEFT]; rightDigitNum = temp[SEGDIGIT_RIGHT]; pthread_mutex_unlock(&zenDisplay_mutex); } void zenSegDisplayStart() { // Start the thread pthread_create(&zenDisplay_id, NULL, &segDisplayThread, NULL); } void zenSegDisplayStop() { zenSegDisplayDigitOff(SEGDIGIT_BOTH); pthread_join(zenDisplay_id, NULL); }<file_sep>/floppyBirbGame.h // floppyBirbGame.h // Module to start/stop the Floppy Birb game thread and provide routines to retrieve game data. #ifndef _FLOPPYBIRBGAME_H_ #define _FLOPPYBIRBGAME_H_ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <pthread.h> #include <netdb.h> #include <string.h> #include <unistd.h> #include <time.h> #include "zen_joystick.h" #include "zen_accelerometer.h" #include "zen_buzzer.h" #include "ext_8x8led.h" #include "zen_segdisplay.h" typedef struct { int x; int y; } birdgame_coords; //------- function prototypes ---------------------- // Start the game thread // void floppyBirbGame_start(void); // Stop the game thread // void floppyBirbGame_stop(void); // Get game data // *ballx = current ball X position (0 to 7), 0 is leftmost, 7 is rightmost LED dot // *bally = current ball Y position (0 to 7), 0 is uppermost, 7 is lowermost LED dot // // void floppyBirbGame_GetData (int *ballx, int *bally); #endif <file_sep>/udpServer1.h // udpServer.h // Module to spawn a thread to listen to UDP port 12345 // and process commands. #ifndef _UDPSERVER_H_ #define _UDPSERVER_H_ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <pthread.h> #include <netdb.h> #include <string.h> #include <unistd.h> #include "ext_8x8led.h" #include "simonGame.h" #include "catchGame.h" #include "snakeGame.h" #include "balanceGame.h" // Begin/end the background thread which listens to UDP void UDPServer_startListening(void); void UDPServer_stopListening(void); #endif <file_sep>/zen_accelerometer.c #include "zen_accelerometer.h" //------------ variables and definitions ----------------------- static int i2cFileDesc; //------------ functions --------------------------------------- //***** static functions ****************************** //***** public functions ****************************** //***************************************************** // Initializes Zen Cape accelerometer. // Return value: true=success, false=fail //***************************************************** _Bool zenAccelerometerInit() { //---------------------------------------------------------------- // Initialize I2C interface and enable accelerometer. //---------------------------------------------------------------- // Open I2C driver i2cFileDesc = open("/dev/i2c-1", O_RDWR); if (i2cFileDesc < 0) { printf("I2C DRV: Unable to open bus for read/write (/dev/i2c-1)\n"); return false; } // Set slave address to 0x1C int result = ioctl(i2cFileDesc, I2C_SLAVE, 0x1C); if (result < 0) { printf("Unable to set I2C device to slave address to 0x1C.\n"); return false; } // Set register 0x2A to 0x04 and then 0x05 unsigned char buff[2]; buff[0] = 0x2A; buff[1] = 0x04; result = write(i2cFileDesc, buff, 2); if (result != 2) { printf("ERROR! Unable to write i2c register\n"); return false; } buff[1] = 0x05; result = write(i2cFileDesc, buff, 2); if (result != 2) { printf("ERROR! Unable to write i2c register\n"); return false; } close(i2cFileDesc); return true; // success } //***************************************************** // Read X, Y, Z values from Zen Cape accelerometer. // Return value: true=success, false=fail //***************************************************** _Bool zenAccelerometerRead(int *xval, int *yval, int *zval) { // Open I2C driver i2cFileDesc = open("/dev/i2c-1", O_RDWR); if (i2cFileDesc < 0) { printf("I2C DRV: Unable to open bus for read/write (/dev/i2c-1)\n"); return false; } // Set slave address to 0x1C int result = ioctl(i2cFileDesc, I2C_SLAVE, 0x1C); if (result < 0) { printf("Unable to set I2C device to slave address to 0x1C.\n"); return false; } // Set register to 0x00 unsigned char buff[8]; buff[0] = 0x00; result = write(i2cFileDesc, buff, 1); if (result != 1) { printf("ERROR! Unable to read i2c register\n"); return false; } result = read(i2cFileDesc, buff, 7); // Read 7 bytes status,XMSB,XLSB,YMSB,YLSB,ZMSB,ZLSB if (result != 7) { printf("ERROR! Unable to read i2c register\n"); return false; } // Form X, Y, Z 12-bit signed values *xval = (((int) buff[1]) << 8) + buff[2]; *xval >>= 4; if (*xval > 2047) *xval -= 4096; *yval = (((int) buff[3]) << 8) + buff[4]; *yval >>= 4; if (*yval > 2047) *yval -= 4096; *zval = (((int) buff[5]) << 8) + buff[6]; *zval >>= 4; if (*zval > 2047) *zval -= 4096; close(i2cFileDesc); return true; // success } <file_sep>/balanceGame.h // balanceGame.h // Module to start/stop the "Balance" game thread and provide routines to retrieve game data. #ifndef _BALANCEGAME_H_ #define _BALANCEGAME_H_ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <pthread.h> #include <netdb.h> #include <string.h> #include <unistd.h> #include <time.h> #include "zen_accelerometer.h" #include "zen_buzzer.h" #include "ext_8x8led.h" #include "zen_segdisplay.h" //------- function prototypes ---------------------- // Start the game thread // void balanceGame_start(void); // Stop the game thread // void balanceGame_stop(void); // Get game data // *ballx = current ball X position (0 to 7), 0 is leftmost, 7 is rightmost LED dot // *bally = current ball Y position (0 to 7), 0 is uppermost, 7 is lowermost LED dot // void balanceGame_GetData (int *ballx, int *bally); #endif <file_sep>/simonGame.h #ifndef _SIMONGAME_H_ #define _SIMONGAME_H_ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <pthread.h> #include <netdb.h> #include <string.h> #include <unistd.h> #include <time.h> #include "zen_joystick.h" #include "zen_buzzer.h" #include "ext_8x8led.h" #include "ext_buttons.h" #include "zen_segdisplay.h" void simonGame_start(void); void simonGame_stop(void); #endif<file_sep>/ext_8x8led.c // ext_8x8led.c // Routines/definitions for external 8x8 LED display #include "ext_8x8led.h" //------------ variables and definitions ----------------------- static unsigned char localbuffer[8]; static unsigned char displaybuffer[17]; // 1 command byte + 16 bytes (rows), 8 bits (columns) per byte static int i2cFileDesc; static enum display_rotation disprotation = DISPLAY_ROTATE0; static pthread_mutex_t localbufferStat = PTHREAD_MUTEX_INITIALIZER; //------------ functions --------------------------------------- //***** static functions ****************************** static void assert_blinktype_OK (enum ht16k33_blink blinktype) { assert((blinktype >= HT16K33_BLINK_OFF) && (blinktype <= HT16K33_BLINK_0_5HZ)); } //***************************************************** // Remap an 8x8 icon so that it displays correctly on 8x8 LED with rotation. // "rot" parameter specifies the rotation (0, 90, 180, 270 degrees). //***************************************************** static void extLED8x8RemapIcon(unsigned char *img, unsigned char *outimg) { unsigned char tmpbyte; unsigned char tmpin; int k; int j; // 270 degrees rotation if (disprotation == DISPLAY_ROTATE270) { for (k = 0; k < 8; k++) { tmpin = img[k]; if (tmpin & 0x80) tmpin = 0x01 | (tmpin << 1); else tmpin = (tmpin << 1); for (j = 0; j < 8; j++) { tmpbyte <<= 1; if (tmpin & 1) tmpbyte |= 0x01; tmpin >>= 1; } outimg[k] = tmpbyte; } } // 0 degrees rotation else if (disprotation == DISPLAY_ROTATE0) { unsigned char tmpbuff[8]; for (k = 0; k < 8; k++) { for (j = 0; j < 8; j++) { tmpbyte <<= 1; if (img[j] & (1<<k)) tmpbyte |= 0x01; } if (tmpbyte & 0x01) tmpbyte = 0x80 | (tmpbyte >> 1); else tmpbyte = (tmpbyte >> 1); tmpbuff[k] = tmpbyte; } for (k = 0; k < 8; k++) { outimg[k] = tmpbuff[7-k]; } } // 90 degrees rotation else if (disprotation == DISPLAY_ROTATE90) { for (k = 0; k < 8; k++) { tmpin = img[k]; if (tmpin & 0x01) tmpin = 0x80 | (tmpin >> 1); else tmpin = (tmpin >> 1); outimg[k] = tmpin; } for (k = 0; k < 4; k++) { tmpbyte = outimg[k]; outimg[k] = outimg[7-k]; outimg[7-k] = tmpbyte; } } // 180 degrees rotation else { unsigned char tmpbuff[8]; for (k = 0; k < 8; k++) { for (j = 0; j < 8; j++) { tmpbyte >>= 1; if (img[j] & (1<<k)) tmpbyte |= 0x80; } if (tmpbyte & 0x01) tmpbyte = 0x80 | (tmpbyte >> 1); else tmpbyte = (tmpbyte >> 1); tmpbuff[k] = tmpbyte; } for (k = 0; k < 8; k++) { outimg[k] = tmpbuff[7-k]; } } } //***** public functions ****************************** //***************************************************** // Initializes the 8x8 LED matrix // Return value: true=success, false=fail //***************************************************** _Bool extLED8x8Init() { //---------------------------------------------------------------- // Initialize display buffer //---------------------------------------------------------------- displaybuffer[0] = HT16K33_CMD_DISPRAM; for (int k = 0; k < 8; k++) localbuffer[k] = 0; for (int k = 1; k < 17; k++) displaybuffer[k] = 0; //---------------------------------------------------------------- // Open I2C interface //---------------------------------------------------------------- // Open I2C driver i2cFileDesc = open("/dev/i2c-1", O_RDWR); if (i2cFileDesc < 0) { printf("I2C DRV: Unable to open bus for read/write (/dev/i2c-1)\n"); return false; } // Set slave address to 0x70 int result = ioctl(i2cFileDesc, I2C_SLAVE, 0x70); if (result < 0) { printf("Unable to set I2C device to slave address to 0x70.\n"); return false; } //---------------------------------------------------------------- // Initialize display RAM //---------------------------------------------------------------- result = write(i2cFileDesc, displaybuffer, 17); if (result != 17) { printf("ERROR! Unable to write i2c register\n"); return false; } //---------------------------------------------------------------- // Turn on oscillator //---------------------------------------------------------------- unsigned char buff[2]; buff[0] = HT16K33_CMD_SYSSETUP | 0x01; result = write(i2cFileDesc, buff, 1); if (result != 1) { printf("ERROR! Unable to write i2c register\n"); return false; } //---------------------------------------------------------------- // Set max. brightness (0x0F) //---------------------------------------------------------------- buff[0] = HT16K33_CMD_BRIGHTNESS | 0x0F; result = write(i2cFileDesc, buff, 1); if (result != 1) { printf("ERROR! Unable to write i2c register\n"); return false; } //---------------------------------------------------------------- // Turn on LEDs with no blinking //---------------------------------------------------------------- buff[0] = HT16K33_CMD_DISPSETUP | 0x01; // Bit 0=1 turns on display, Bits 2-1=0 means no blinking result = write(i2cFileDesc, buff, 1); if (result != 1) { printf("ERROR! Unable to write i2c register\n"); return false; } close(i2cFileDesc); return true; // success } //***************************************************** // Updates the 8x8 LED matrix display RAM (pixel) data // Return value: true=success, false=fail //***************************************************** _Bool extLED8x8DisplayUpdate() { //---------------------------------------------------------------- // Remap local buffer to display buffer for sending //---------------------------------------------------------------- unsigned char tmpbuff[8]; extLED8x8RemapIcon(localbuffer, tmpbuff); for (int k = 0; k < 8; k++) { displaybuffer[1+k*2] = tmpbuff[k]; } //---------------------------------------------------------------- // Open I2C interface //---------------------------------------------------------------- // Open I2C driver i2cFileDesc = open("/dev/i2c-1", O_RDWR); if (i2cFileDesc < 0) { printf("I2C DRV: Unable to open bus for read/write (/dev/i2c-1)\n"); return false; } // Set slave address to 0x70 int result = ioctl(i2cFileDesc, I2C_SLAVE, 0x70); if (result < 0) { printf("Unable to set I2C device to slave address to 0x70.\n"); return false; } //---------------------------------------------------------------- // Write display RAM //---------------------------------------------------------------- result = write(i2cFileDesc, displaybuffer, 17); if (result != 17) { printf("ERROR! Unable to write i2c register\n"); return false; } close(i2cFileDesc); return true; // success } //***************************************************** // Turn off the 8x8 LED matrix. // Return value: true=success, false=fail //***************************************************** _Bool extLED8x8DisplayOff() { //---------------------------------------------------------------- // Open I2C interface //---------------------------------------------------------------- // Open I2C driver i2cFileDesc = open("/dev/i2c-1", O_RDWR); if (i2cFileDesc < 0) { printf("I2C DRV: Unable to open bus for read/write (/dev/i2c-1)\n"); return false; } // Set slave address to 0x70 int result = ioctl(i2cFileDesc, I2C_SLAVE, 0x70); if (result < 0) { printf("Unable to set I2C device to slave address to 0x70.\n"); return false; } //---------------------------------------------------------------- // Turn off display //---------------------------------------------------------------- unsigned char buff[2]; buff[0] = HT16K33_CMD_DISPSETUP; // Bit0=0 turns off display result = write(i2cFileDesc, buff, 1); if (result != 1) { printf("ERROR! Unable to write i2c register\n"); return false; } close(i2cFileDesc); return true; // success } //***************************************************** // Turn on the 8x8 LED matrix. // Parameter "blinktype" specifies the blinking type. // Return value: true=success, false=fail //***************************************************** _Bool extLED8x8DisplayOn(enum ht16k33_blink blinktype) { // Parameters range checking assert_blinktype_OK (blinktype); //---------------------------------------------------------------- // Open I2C interface //---------------------------------------------------------------- // Open I2C driver i2cFileDesc = open("/dev/i2c-1", O_RDWR); if (i2cFileDesc < 0) { printf("I2C DRV: Unable to open bus for read/write (/dev/i2c-1)\n"); return false; } // Set slave address to 0x70 int result = ioctl(i2cFileDesc, I2C_SLAVE, 0x70); if (result < 0) { printf("Unable to set I2C device to slave address to 0x70.\n"); return false; } //---------------------------------------------------------------- // Turn off display //---------------------------------------------------------------- unsigned char buff[2]; buff[0] = HT16K33_CMD_DISPSETUP | 0x01 | (blinktype<<1); result = write(i2cFileDesc, buff, 1); if (result != 1) { printf("ERROR! Unable to write i2c register\n"); return false; } close(i2cFileDesc); return true; // success } //***************************************************** // Set brightness level of 8x8 LED matrix. // Parameter "brightness" specifies the brightness level (0 to 15). // Return value: true=success, false=fail //***************************************************** _Bool extLED8x8DisplayBrightness(unsigned char brightness) { //---------------------------------------------------------------- // Open I2C interface //---------------------------------------------------------------- // Open I2C driver i2cFileDesc = open("/dev/i2c-1", O_RDWR); if (i2cFileDesc < 0) { printf("I2C DRV: Unable to open bus for read/write (/dev/i2c-1)\n"); return false; } // Set slave address to 0x70 int result = ioctl(i2cFileDesc, I2C_SLAVE, 0x70); if (result < 0) { printf("Unable to set I2C device to slave address to 0x70.\n"); return false; } //---------------------------------------------------------------- // Turn off display //---------------------------------------------------------------- unsigned char buff[2]; if (brightness > 15) brightness = 15; buff[0] = HT16K33_CMD_BRIGHTNESS | brightness; result = write(i2cFileDesc, buff, 1); if (result != 1) { printf("ERROR! Unable to write i2c register\n"); return false; } close(i2cFileDesc); return true; // success } //============== Drawing routines ======================================== //***************************************************** // Set rotation of 8x8 display. 0, 90, 180, or 270 clockwise. //***************************************************** void extLED8x8SetDisplayRotation(enum display_rotation rotval) { disprotation = rotval; } //***************************************************** // Fill local buffer with pixel value. //***************************************************** void extLED8x8FillPixel(unsigned char pixelval) { pthread_mutex_lock(&localbufferStat); { for (int k = 0; k < 8; k++) { if (pixelval) localbuffer[k] = 0xFF; else localbuffer[k] = 0x00; } } pthread_mutex_unlock(&localbufferStat); } //***************************************************** // Draw a pixel into the local buffer. // Top, left corner pixel coordinate is (0,0). // Bottom, right corner pixel coordinate is (7,7). //***************************************************** void extLED8x8DrawPixel(unsigned int x, unsigned int y, unsigned char pixelval) { pthread_mutex_lock(&localbufferStat); { // Only draw pixel if it is inbounds (x=0 to 7, y=0 to 7) if ((x < 8) && (y < 8)) { if (pixelval) { localbuffer[y] |= (0x80 >> x); } else { localbuffer[y] &= ~(0x80 >> x); } } } pthread_mutex_unlock(&localbufferStat); } //***************************************************** // Load an 8x8 image into local buffer. //***************************************************** void extLED8x8LoadImage(unsigned char *img) { pthread_mutex_lock(&localbufferStat); { for (int k = 0; k < 8; k++) { localbuffer[k] = img[k]; } } pthread_mutex_unlock(&localbufferStat); } //***************************************************** // Scroll 7-bit ASCII text one character at a time through the 8x8 matrix // txtstr: text string to display // fontset: 128-character 8x8 font set // scrollmsdelay: pixel shift delay in milliseconds // scrolldir: scroll direction //***************************************************** void extLED8x8ScrollText(char *txtstr, unsigned char *fontset, int scrollmsdelay, enum scroll_direction scrolldir) { struct timespec reqDelay; reqDelay.tv_sec = 0; reqDelay.tv_nsec = scrollmsdelay*1000000; // Go through each character while (*(txtstr+1) != 0) { unsigned char fontchar1[8]; unsigned char fontchar2[8]; // Copy current and next font character for (int k = 0; k < 8; k++) { fontchar1[k] = fontset[(txtstr[0] * 8) + k]; if (txtstr[1] != 0) fontchar2[k] = fontset[(txtstr[1] * 8) + k]; else fontchar2[k] = 0; } // Scroll through 8 pixels of font character for (int pixoffset = 0; pixoffset < 8; pixoffset++) { pthread_mutex_lock(&localbufferStat); { // Compose local buffer according scroll direction if (scrolldir == SCROLL_LEFT) { for (int line = 0; line < 8; line++) { unsigned char tmpbyte; tmpbyte = fontchar1[line] << pixoffset; tmpbyte = tmpbyte | (fontchar2[line] >> (8 - pixoffset)); localbuffer[line] = tmpbyte; } } else if (scrolldir == SCROLL_RIGHT) { for (int line = 0; line < 8; line++) { unsigned char tmpbyte; tmpbyte = fontchar1[line] >> pixoffset; tmpbyte = tmpbyte | (fontchar2[line] << (8 - pixoffset)); localbuffer[line] = tmpbyte; } } else if (scrolldir == SCROLL_UP) { for (int line = 0; line < 8; line++) { if (line < (8 - pixoffset)) localbuffer[line] = fontchar1[line+pixoffset]; else localbuffer[line] = fontchar2[line-(8-pixoffset)]; } } else { // SCROLL_DOWN for (int line = 0; line < 8; line++) { if (line < pixoffset) localbuffer[line] = fontchar2[line+(8-pixoffset)]; else localbuffer[line] = fontchar1[line-pixoffset]; } } } pthread_mutex_unlock(&localbufferStat); // Update display extLED8x8DisplayUpdate(); nanosleep(&reqDelay, (struct timespec *) NULL); } txtstr++; } nanosleep(&reqDelay, (struct timespec *) NULL); } //***************************************************** // Countdown 3,2,1 //***************************************************** void extLED8x8CountDown321(unsigned char *font) { struct timespec reqDelay; reqDelay.tv_sec = 1; reqDelay.tv_nsec = 0; extLED8x8LoadImage(&(font['3'*8])); extLED8x8DisplayUpdate(); nanosleep(&reqDelay, (struct timespec *) NULL); extLED8x8LoadImage(&(font['2'*8])); extLED8x8DisplayUpdate(); nanosleep(&reqDelay, (struct timespec *) NULL); extLED8x8LoadImage(&(font['1'*8])); extLED8x8DisplayUpdate(); nanosleep(&reqDelay, (struct timespec *) NULL); } //***************************************************** // LED logo for exiting a game //***************************************************** void extLED8x8ExitGame(unsigned char *font) { struct timespec reqDelay; reqDelay.tv_sec = 1; reqDelay.tv_nsec = 0; extLED8x8LoadImage(&(font['B'*8])); extLED8x8DisplayUpdate(); nanosleep(&reqDelay, (struct timespec *) NULL); extLED8x8LoadImage(&(font['Y'*8])); extLED8x8DisplayUpdate(); nanosleep(&reqDelay, (struct timespec *) NULL); extLED8x8LoadImage(&(font['E'*8])); extLED8x8DisplayUpdate(); nanosleep(&reqDelay, (struct timespec *) NULL); } //***************************************************** // Get local display buffer data //***************************************************** void extLED8x8GetLocalBuffer(unsigned char *copybuff) { pthread_mutex_lock(&localbufferStat); { for (int k = 0; k < 8; k++) copybuff[k] = localbuffer[k]; } pthread_mutex_unlock(&localbufferStat); } <file_sep>/balanceGame.c // balanceGame.c // Module to start/stop the "Balance" game thread and provide routines to retrieve game data. #include "balanceGame.h" //------------ variables and definitions ----------------------- static pthread_t balanceGame_id; static pthread_mutex_t balanceGameStat = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t balanceGameData = PTHREAD_MUTEX_INITIALIZER; static int xpos, ypos; extern unsigned char font8x8[]; //------------ functions --------------------------------------- //***** static functions ****************************** int combine(int x, int y) { int times = 1; while (times <= y) { times *= 10; } return x*times + y; } //------------------------------------------------------- // "Balance the ball" game. //------------------------------------------------------- static void *balanceGameThread() { struct timespec reqDelay; int xval, yval, zval; // Draw ball in center of matrix extLED8x8FillPixel(0); xpos = 3; ypos = 3; extLED8x8DrawPixel(xpos, ypos, 1); extLED8x8DisplayUpdate(); // Initalize seg display. // Bottom Left pixel is (0,0) top right pixel is (8,8) zenSegDisplayUpdateNum(combine((xpos + 1), (ypos + 1))); reqDelay.tv_sec = 0; reqDelay.tv_nsec = 100000000; // 100ms sampling rate while (1) { zenAccelerometerRead(&xval, &yval, &zval); pthread_mutex_lock(&balanceGameData); { if (xval > 128) { if (xpos < 7) { xpos++; } } else if (xval < -128) { if (xpos > 0) { xpos--; } } if (yval < -128) { if (ypos < 7) { ypos++; } } else if (yval > 128) { if (ypos > 0) { ypos--; } } zenSegDisplayUpdateNum(combine((xpos + 1), (ypos + 1))); // Update x y coordinates to seg display } pthread_mutex_unlock(&balanceGameData); extLED8x8FillPixel(0); extLED8x8DrawPixel(xpos, ypos, 1); extLED8x8DisplayUpdate(); // sampling delay nanosleep(&reqDelay, (struct timespec *) NULL); // Check for request to terminate thread int lockstat; lockstat = pthread_mutex_trylock(&balanceGameStat); if (lockstat == 0) { // lock acquired (0) means terminate pthread_exit(0); } } pthread_exit(0); } //***** public functions ****************************** void balanceGame_start (void) { printf("Starting game of 'Balance'\n"); // 3, 2, 1 count down extLED8x8CountDown321(font8x8); pthread_mutex_init(&balanceGameStat, NULL); // Lock mutex used by thread to check for request to end the thread pthread_mutex_lock(&balanceGameStat); // Start the thread pthread_create(&balanceGame_id, NULL, &balanceGameThread, NULL); } void balanceGame_stop (void) { // Unlock mutex to let sorting thread know about request to finish pthread_mutex_unlock(&balanceGameStat); printf("Stopping game of 'Balance'\n"); // Exit game logo extLED8x8ExitGame(font8x8); // Wait for thread to finish pthread_join(balanceGame_id, NULL); } void balanceGame_GetData (int *ballx, int *bally) { pthread_mutex_lock(&balanceGameData); { *ballx = xpos; *bally = ypos; } pthread_mutex_unlock(&balanceGameData); } <file_sep>/ext_photoresistor.h // ext_photoresistor.h // Routines/definitions for a photoresistor // By <NAME> #ifndef EXT_PHOTORESISTOR_H #define EXT_PHOTORESISTOR_H #include <stdbool.h> #include <assert.h> #include <stdio.h> //------- function prototypes ---------------------- // Read A2D value of potentiometer. // Return value: 0 to 4095 (inclusive), or <0 if error occurred. int extPhotoresistorReadA2DValue(); // Read voltage of potentiometer. // Return value: 0 to 1.8V (inclusive), or <0 if error occurred. double extPhotoresistorReadVoltage(); #endif <file_sep>/bbg_led.c #include "bbg_led.h" #include <string.h> #include <stdio.h> #include <assert.h> //------------ variables and definitions ----------------------- // LED filename definitions #define LEDS_FILEPATH_PREFIX "/sys/class/leds/beaglebone:green:" static char *led_foldersel[4] = { "usr0/", "usr1/", "usr2/", "usr3/" }; // LED trigger strings static char *led_trigstring[3] = { "none", "timer", "heartbeat" }; //------------ functions --------------------------------------- //***** static functions ****************************** static void assert_bbgLED_OK (enum bbgLED led) { assert((led >= BBG_LED0) && (led <= BBG_LED3)); } static void assert_bbgLED_TrigMode_OK (enum bbgLEDTrigMode trigmode) { assert((trigmode >= NONE) && (trigmode <= HEARTBEAT)); } static void assert_bbgLED_OffOn_OK (enum bbgLEDOffOn ledoffon) { assert((ledoffon >= BBG_LED_OFF) && (ledoffon <= BBG_LED_ON)); } //***** public functions ****************************** // Initialize an LED trigger mode. // Return value: true=successful, false=not successful _Bool bbgLED_trigmode(enum bbgLED led, enum bbgLEDTrigMode trigmode) { char filepath[128]; // Parameters range checking assert_bbgLED_OK(led); assert_bbgLED_TrigMode_OK(trigmode); // Compose filename filepath[0] = 0; strcat(filepath, LEDS_FILEPATH_PREFIX); strcat(filepath, led_foldersel[led]); strcat(filepath, "trigger"); FILE *LedTriggerFile = fopen(filepath, "w"); if (LedTriggerFile == NULL) { printf("ERROR OPENING %s.\r\n", filepath); return false; } // Write to "trigger" file fprintf(LedTriggerFile, "%s", led_trigstring[trigmode]); // Make sure to close file fclose(LedTriggerFile); return true; } // LED on/off // Return value: true=successful, false=not successful _Bool bbgLED_set(enum bbgLED led, enum bbgLEDOffOn ledoffon) { char filepath[128]; // Parameters range checking assert_bbgLED_OK(led); assert_bbgLED_OffOn_OK(ledoffon); // Compose filename filepath[0] = 0; strcat(filepath, LEDS_FILEPATH_PREFIX); strcat(filepath, led_foldersel[led]); strcat(filepath, "brightness"); FILE *LedBrightnessFile = fopen(filepath, "w"); if (LedBrightnessFile == NULL) { printf("ERROR OPENING %s.\r\n", filepath); return false; } // Write to "brightness" file fprintf(LedBrightnessFile, "%d", ledoffon); // Make sure to close file fclose(LedBrightnessFile); return true; } // All LEDs on/off // Return value: true=successful, false=not successful _Bool bbgLED_setall(enum bbgLEDOffOn ledoffon) { for (int k = 0; k < MAX_BBG_LEDS; k++) { if (bbgLED_set(k, ledoffon) == false) return false; } return true; }
d3b456696a09404437d9e19ff00119d77b373461
[ "JavaScript", "C", "Makefile", "Markdown" ]
35
C
churellano/minigames-console
300c350315d436ae6ee88befc40e1a30457537a3
fd2dd9ebab379fa0646f1a51c8b67f1105a2093d
refs/heads/master
<repo_name>jhjguxin/multi_xml<file_sep>/spec/helper.rb require 'simplecov' require 'coveralls' SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[ SimpleCov::Formatter::HTMLFormatter, Coveralls::SimpleCov::Formatter ] SimpleCov.start require 'multi_xml' require 'rspec' RSpec.configure do |config| config.expect_with :rspec do |c| c.syntax = :expect end end def jruby?(platform = RUBY_PLATFORM) "java" == platform end def rubinius?(platform = defined?(RUBY_ENGINE) && RUBY_ENGINE) "rbx" == platform end
c1a9c8a6dec16c902723a4f4c2dc7215d1a03a9d
[ "Ruby" ]
1
Ruby
jhjguxin/multi_xml
16f2889ff6e7ec43d1d80de1c60652cdda18fc42
db5d13160089f05e81321142c3f902f189d6526b
refs/heads/master
<file_sep>Rails.application.routes.draw do root 'static#index' get 'static/team' get '/team', to: 'static#team' get 'static/contact' get '/contact', to: 'static#contact' get '/new_gossips', to: 'create_gossip#new_gossip' post '/new_gossips', to: "create_gossip#new_gossip" get '/:id', to: 'gossip#one_gossip' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end <file_sep># Gossip Project > Pair programming avec @Thierry ## Lien vers le site en ligne Gossip Project ! https://thegossip.herokuapp.com/ <file_sep>class CreateGossipController < ApplicationController def new_gossip @gossips = Gossip.all @new_gossip = Gossip.create end end <file_sep>require 'test_helper' class CreateGossipControllerTest < ActionDispatch::IntegrationTest test "should get new_gossip" do get create_gossip_new_gossip_url assert_response :success end end <file_sep>class GossipController < ApplicationController def create end def one_gossip end end <file_sep>class Gossip < ApplicationRecord belongs_to :author, class_name: 'User' end <file_sep>class User < ApplicationRecord has_many :gossips, foreign_key: :author end
b535be4dff3dcece3ba9597ee3b14cda63ce8a53
[ "Markdown", "Ruby" ]
7
Ruby
VAJangoFett/Gossip_Project
2f423d3a24e1cc88de5198a6ac0b761f3c2a625b
e3e69f1616c280118176130bc6d361f7dd8f8900
refs/heads/master
<repo_name>mcvitanic/ProgrammingAssignment2<file_sep>/cachematrix.R # Example usage: # > mm <- matrix(rnorm(9), nrow = 3) // Create a matrix mm 3 x 3 # > cmm <- makeCacheMatrix(mm) // Create our special matrix # > cmm$get() // Return the matrix # > cacheSolve(cmm) // Return the inverse # > cacheSolve(cmm) // Call the 2nd time, so return the cached inverse # makeCacheMatrix is a function that returns a list of functions # Its puspose is to store a martix and a cached value of the inverse of the matrix. Contains the following functions: # setMatrix sets the value of a matrix # getMatrix gets the value of a matrix # cacheInverse gets the cahced value (inverse of the matrix) # getInverse gets the cahced value (inverse of the matrix) # makeCacheMatrix <- function(x = matrix()) { inv <- NULL set <- function(y) { x <<- y inv <<- NULL } get <- function() x setinv <- function(inverse) inv <<- inverse getinv <- function() inv list(set = set, get = get, setinv = setinv, getinv = getinv) } # cacheSolve: Compute the inverse of the matrix. If the inverse is already calculated before, it returns the cached inverse. cacheSolve <- function(x, ...) { inv <- x$getinv() # If the inverse is already calculated, return it if (!is.null(inv)) { message("getting cached data") return(inv) } # The inverse is not yet calculated, so we need to calculate it data <- x$get() inv <- solve(data, ...) # Cache the inverse x$setinv(inv) # Return the inverse inv }
b8ceb7592358f4b800aa9021c6b5f935309f81d6
[ "R" ]
1
R
mcvitanic/ProgrammingAssignment2
d0b4792d57e38849d935c3fb872b6435a88e550c
828eb67bacf507417e784136f1d8f4b02defd4e6
refs/heads/master
<repo_name>supermanc88/TdiDriver<file_sep>/TdiDriverTest/TdiDriver.cpp #include "TdiDriver.h" #ifdef __cplusplus extern "C" { #endif PDEVICE_OBJECT g_TcpFltObj = NULL; PDEVICE_OBJECT g_UdpFltObj = NULL; PDEVICE_OBJECT g_TcpOldObj = NULL; PDEVICE_OBJECT g_UdpOldObj = NULL; typedef struct { TDI_ADDRESS_INFO *tai; PFILE_OBJECT fileObj; } TDI_CREATE_ADDROBJ2_CTX; typedef struct _IP_ADDRESS { union { ULONG ipInt; UCHAR ipUChar[4]; }; }IP_ADDRESS, *PIP_ADDRESS; NTKERNELAPI NTSTATUS IoCheckEaBufferValidity( PFILE_FULL_EA_INFORMATION EaBuffer, ULONG EaLength, PULONG ErrorOffset ); USHORT TdiFilter_Ntohs(IN USHORT v) { return (((UCHAR)(v >> 8)) | (v & 0xff) << 8); }; ULONG TdiFilter_Ntohl(IN ULONG v) //颠倒IP地址的顺序 { return ((v & 0xff000000) >> 24 | (v & 0xff0000) >> 8 | (v & 0xff00) << 8 | ((UCHAR)v) << 24); }; VOID DriverUnload(PDRIVER_OBJECT DriverObject) { KdPrint(("TdiDriver: 驱动卸载\n")); DetachAndDeleteDevie(DriverObject, g_TcpFltObj, g_TcpOldObj); // DetachAndDeleteDevie(DriverObject, g_UdpFltObj, g_UdpOldObj); } NTSTATUS DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath) { NTSTATUS status = STATUS_SUCCESS; int i = 0; KdPrint(("TdiDriver: 驱动加载\n")); DriverObject->DriverUnload = DriverUnload; for (i=0; i<IRP_MJ_MAXIMUM_FUNCTION; i++) { DriverObject->MajorFunction[i] = TdiPassThrough; } DriverObject->MajorFunction[IRP_MJ_INTERNAL_DEVICE_CONTROL] = TdiInternalDeviceControl; //主要操作都在这个里面 DriverObject->MajorFunction[IRP_MJ_CREATE] = TdiFilterCreate; //开始创建并绑定设备 CreateAndAttachDevice(DriverObject, &g_TcpFltObj, &g_TcpOldObj, TCP_DEVICE_NAME); // CreateAndAttachDevice(DriverObject, &g_UdpFltObj, &g_UdpOldObj, UDP_DEVICE_NAME); return status; } NTSTATUS CreateAndAttachDevice(PDRIVER_OBJECT DriverObject, PDEVICE_OBJECT * fltObj, PDEVICE_OBJECT * oldObj, PWCHAR deviceName) { NTSTATUS status; UNICODE_STRING deviceNameStr; status = IoCreateDevice(DriverObject, 0, NULL, FILE_DEVICE_UNKNOWN, 0, TRUE, fltObj); if(!NT_SUCCESS(status)) { KdPrint(("TdiDriver: 创建设备失败\n")); return status; } (*fltObj)->Flags |= DO_DIRECT_IO; //开始绑定指定的设备 RtlInitUnicodeString(&deviceNameStr, deviceName); status = IoAttachDevice(*fltObj, &deviceNameStr, oldObj); if(!NT_SUCCESS(status)) { KdPrint(("TdiDriver: 绑定设备%wZ失败\n", &deviceNameStr)); return status; } return STATUS_SUCCESS; } VOID DetachAndDeleteDevie(PDRIVER_OBJECT DriverObject, PDEVICE_OBJECT fltObj, PDEVICE_OBJECT oldObj) { IoDetachDevice(oldObj); IoDeleteDevice(fltObj); } NTSTATUS TdiInternalDeviceControl(PDEVICE_OBJECT DeviceObject, PIRP Irp) { PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp); NTSTATUS status; PTRANSPORT_ADDRESS transportAddress = NULL; PTDI_REQUEST_KERNEL_CONNECT tdiReqKelConnect = NULL; switch (irpStack->MinorFunction) { case TDI_CONNECT: { //创建连接的时候走这个流程 KdPrint(("Tdi Driver: TDI_CONNECT!\n")); tdiReqKelConnect = (PTDI_REQUEST_KERNEL_CONNECT)(&irpStack->Parameters); if(!tdiReqKelConnect->RequestConnectionInformation) { KdPrint(("Tdi Driver: no request!\n")); IoSkipCurrentIrpStackLocation(Irp); status = IoCallDriver(g_TcpOldObj, Irp); } if(tdiReqKelConnect->RequestConnectionInformation->RemoteAddressLength == 0) { KdPrint(("Tdi Driver: RemoteAddressLength=0\n")); IoSkipCurrentIrpStackLocation(Irp); status = IoCallDriver(g_TcpOldObj, Irp); } transportAddress = (PTRANSPORT_ADDRESS)(tdiReqKelConnect->RequestConnectionInformation->RemoteAddress); TdiGetAddressInfo(transportAddress); IoSkipCurrentIrpStackLocation(Irp); status = IoCallDriver(g_TcpOldObj, Irp); break; } case TDI_ACCEPT: IoSkipCurrentIrpStackLocation(Irp); status = IoCallDriver(g_TcpOldObj, Irp); break; default: IoSkipCurrentIrpStackLocation(Irp); status = IoCallDriver(g_TcpOldObj, Irp); break; } return status; } NTSTATUS TdiPassThrough(PDEVICE_OBJECT DeviceObject, PIRP Irp) { NTSTATUS status = STATUS_SUCCESS; //如果设备对象是我们要过滤的,直接传给下层的设备对象 IoSkipCurrentIrpStackLocation(Irp); status = IoCallDriver(g_TcpOldObj, Irp); return status; } NTSTATUS TdiFilterCreate(PDEVICE_OBJECT DeviceObject, PIRP Irp) { KdPrint(("Tdi Driver: TdiFilterCreate\n")); PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(Irp); PFILE_FULL_EA_INFORMATION ea = NULL; ULONG ErrorOffset = 0; NTSTATUS status = STATUS_UNSUCCESSFUL; ea = (PFILE_FULL_EA_INFORMATION)Irp->AssociatedIrp.SystemBuffer; status = IoCheckEaBufferValidity(ea, irpSp->Parameters.Create.EaLength, &ErrorOffset); if(NT_SUCCESS(status)) { if (TDI_TRANSPORT_ADDRESS_LENGTH == ea->EaNameLength && TDI_TRANSPORT_ADDRESS_LENGTH == RtlCompareMemory(ea->EaName, TdiTransportAddress, TDI_TRANSPORT_ADDRESS_LENGTH)) { PTRANSPORT_ADDRESS transportAddress; transportAddress = (PTRANSPORT_ADDRESS)((PUCHAR)ea + FIELD_OFFSET(FILE_FULL_EA_INFORMATION, EaName) + TDI_TRANSPORT_ADDRESS_LENGTH + 1); TdiGetAddressInfo(transportAddress); PIRP queryIrp; queryIrp = TdiBuildInternalDeviceControlIrp(TDI_QUERY_INFORMATION, DeviceObject, irpSp->FileObject, NULL, NULL); IoCopyCurrentIrpStackLocationToNext(Irp); IoSetCompletionRoutine(Irp, MyIoCompletionRoutine, queryIrp, TRUE, TRUE, TRUE); return IoCallDriver(g_TcpOldObj, Irp); } } IoSkipCurrentIrpStackLocation(Irp); return IoCallDriver(g_TcpOldObj, Irp); } BOOLEAN TdiGetAddressInfo(PTRANSPORT_ADDRESS transportAddress) { switch (transportAddress->Address->AddressType) { case TDI_ADDRESS_TYPE_IP: { PTDI_ADDRESS_IP tdiAddressIp = (PTDI_ADDRESS_IP)(transportAddress->Address->Address); IP_ADDRESS ipAddress; ipAddress.ipInt = tdiAddressIp->in_addr; USHORT port = TdiFilter_Ntohs(tdiAddressIp->sin_port); KdPrint(("TdiDriver: ip:%d.%d.%d.%d, port:%d\n", ipAddress.ipUChar[0], ipAddress.ipUChar[1], ipAddress.ipUChar[2], ipAddress.ipUChar[3], port)); break; } case TDI_ADDRESS_TYPE_IP6: break; default: break; } return FALSE; } NTSTATUS MyIoCompletionRoutine(PDEVICE_OBJECT DeviceObject, PIRP Irp, PVOID Context) { PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(Irp); PIRP queryIrp = (PIRP)Context; NTSTATUS status = STATUS_SUCCESS; TDI_CREATE_ADDROBJ2_CTX *ctx = NULL; ctx = (TDI_CREATE_ADDROBJ2_CTX *)ExAllocatePool(NonPagedPool, sizeof(TDI_CREATE_ADDROBJ2_CTX)); ctx->fileObj = irpSp->FileObject; ctx->tai = (TDI_ADDRESS_INFO *)ExAllocatePool(NonPagedPool, sizeof(TDI_ADDRESS_INFO) - 1 + TDI_ADDRESS_LENGTH_OSI_TSAP);; PMDL mdl = IoAllocateMdl(ctx->tai, sizeof(TDI_ADDRESS_INFO) - 1 + TDI_ADDRESS_LENGTH_OSI_TSAP, FALSE, FALSE, NULL); MmProbeAndLockPages(mdl, Irp->RequestorMode, IoModifyAccess); TdiBuildQueryInformation(queryIrp, DeviceObject, irpSp->FileObject, QueryAddressInfoCompleteRoutine, // NULL, ctx, // NULL, TDI_QUERY_ADDRESS_INFO, mdl); status = IoCallDriver(g_TcpOldObj, queryIrp); Irp->IoStatus.Status = status; if(Irp->PendingReturned) { IoMarkIrpPending(Irp); } return STATUS_SUCCESS; } NTSTATUS QueryAddressInfoCompleteRoutine(PDEVICE_OBJECT DeviceObject, PIRP Irp, PVOID Context) { TDI_CREATE_ADDROBJ2_CTX * ctx = (TDI_CREATE_ADDROBJ2_CTX *)Context; TA_ADDRESS * addr = ctx->tai->Address.Address; KdPrint(("Tdi Driver QueryAddressInfo %x %u", TdiFilter_Ntohl(((TDI_ADDRESS_IP *)(addr->Address))->in_addr), TdiFilter_Ntohs(((TDI_ADDRESS_IP *)(addr->Address))->sin_port) )); return STATUS_SUCCESS; } #ifdef __cplusplus } #endif <file_sep>/README.md # TdiDriver TdiDriver <file_sep>/TdiDriverTest/TdiDriver.h #pragma once #include <ntddk.h> #include <tdi.h> #include <tdikrnl.h> #define TCP_DEVICE_NAME L"\\Device\\Tcp" #define UDP_DEVICE_NAME L"\\Device\\Udp" #define RAWIP_DEVICE_NAME L"\\Device\\RawIp" #ifdef __cplusplus extern "C" { #endif VOID DriverUnload(PDRIVER_OBJECT DriverObject); NTSTATUS DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath); //创建并绑定指定设备 NTSTATUS CreateAndAttachDevice(PDRIVER_OBJECT DriverObject, PDEVICE_OBJECT * fltObj, PDEVICE_OBJECT * oldObj, PWCHAR deviceName); //取消绑定并删除设备 VOID DetachAndDeleteDevie(PDRIVER_OBJECT DriverObject, PDEVICE_OBJECT fltObj, PDEVICE_OBJECT oldObj); // // 分发函数 // NTSTATUS DeviceDisPatch(PDEVICE_OBJECT DeviceObject, PIRP Irp); // // NTSTATUS TdiControl(PDEVICE_OBJECT DeviceObject, PIRP Irp); NTSTATUS TdiInternalDeviceControl(PDEVICE_OBJECT DeviceObject, PIRP Irp); NTSTATUS TdiPassThrough(PDEVICE_OBJECT DeviceObject, PIRP Irp); //不关心的分发函数全部通过 NTSTATUS TdiFilterCreate(PDEVICE_OBJECT DeviceObject, PIRP Irp); //在这个函数中获取本地ip地址 BOOLEAN TdiGetAddressInfo(PTRANSPORT_ADDRESS transportAddress); //打印ip地址 NTSTATUS MyIoCompletionRoutine( PDEVICE_OBJECT DeviceObject, PIRP Irp, PVOID Context ); NTSTATUS QueryAddressInfoCompleteRoutine( PDEVICE_OBJECT DeviceObject, PIRP Irp, PVOID Context ); #ifdef __cplusplus } #endif
e34888055f34f528b7eb5721f468de543bf5b4c2
[ "Markdown", "C", "C++" ]
3
C++
supermanc88/TdiDriver
40bb9533858355362b6dfd8638bae1cea2f3ed2c
d8d4bed1293c6972f74cd183ffaebf8500e34098
refs/heads/master
<file_sep>require 'rspec' require_relative './bytestring' describe "ByteString" do it 'can convert b64 to hex' do orig = "<KEY>" result = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d" response = ByteString.from_b64(orig).to_hex expect(response).to eq result end end <file_sep>class ByteString attr_reader :bytes def initialize byte_array if byte_array.respond_to? :bytes then @bytes = byte_array.bytes else @bytes = byte_array end end def self.from_text string self.new(string.bytes) end def to_text bytes .map { |b| b.chr } .join end def to_ascii to_text end def to_s to_text end def self.from_hex string vals = string.chars.map do |nib| ByteString.hex_map.index nib end results = [] while vals.size > 0 n1, n2 = vals.shift(2) results << ((n1 << 4) + n2) end self.new(results) end def to_hex bytes.map do |b| f = ByteString.hex_map[(b >> 4)] s = ByteString.hex_map[(b & 0b00001111)] "#{f}#{s}" end.flatten.join end def self.from_b64 text vals = text.chars.map do |c| ByteString.b64_map.index c end results = [] while vals.size > 0 c1, c2, c3, c4 = vals.shift(4) r1 = (c1.to_i << 2) + (c2.to_i >> 4) r2 = ((c2.to_i & 0b00001111) << 4) + (c3.to_i >> 2) r3 = ((c3.to_i & 0b00000011) << 6) + c4.to_i results << r1 << r2 << r3 end self.new(results) end def to_b64 to64 = [] valmap = bytes.dup while valmap.size > 0 set = valmap.shift(3) first = set[0] >> 2 second = ((set[0] & 0b00000011) << 4) + (set[1] >> 4) third = ((set[1] & 0b00001111) << 2) + (set[2] >>6) fourth = set[2] & 0b00111111 to64 << first << second << third << fourth end results = "" to64.each do |c| results += ByteString.b64_map[c] end results end def self.hex_map "0123456789abcdef" end def self.b64_map "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" end def size bytes.size end def hamming_distance other return :NotEqualSize if size != other.size xr = bytes.zip(other.bytes).map { |f, s| f ^ s } hamming_weight(xr) end private def hamming_weight zipped_bytes zipped_bytes.map do |b| b = (((b >> 0) & 0b01010101) + ((b >> 1) & 0b01010101)) b = (((b >> 0) & 0b00110011) + ((b >> 2) & 0b00110011)) (((b >> 0) & 0b00001111) + ((b >> 4) & 0b00001111)) end.reduce(:+) end end <file_sep># Detect single-character XOR # One of the 60-character strings in 4.txt has been encrypted by single-character XOR. # Find it. # (Your code from #3 should help.) require_relative 'base_utils' require_relative 'scores' def challenge4(filename) ln = 0 possibles = [] f = File.open(filename).each_line do |line| line.chomp! break if line == nil || line.size == 0 line = ByteString.from_hex line ln += 1 printf "." score = find_best_english_score(line) possibles << {ln: ln, info: score} end printf "\n" possibles .sort_by { |p| -1 * p[:info][:score] } .first[:info][:line].to_s end<file_sep># Implement repeating-key XOR # Here is the opening stanza of an important work of the English language: # # Burning 'em, if you ain't quick and nimble # I go crazy when I hear a cymbal # # Encrypt it, under the key "ICE", using repeating-key XOR. # # In repeating-key XOR, you'll sequentially apply each byte of the key; the first # byte of plaintext will be XOR'd against I, the next C, the next E, then I again # for the 4th byte, and so on. # # It should come out to: # # 0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272 # a282b2f20430a652e2c652a<KEY> # # Encrypt a bunch of stuff using your repeating-key XOR function. Encrypt your mail. # Encrypt your password file. Your .sig file. Get a feel for it. I promise, we aren't # wasting your time with this. require_relative 'base_utils' def challenge5(input_str) source = ByteString.from_text(input_str) Crypto.xor_with_key(source, "ICE").to_hex end <file_sep>require_relative 'base_utils' def challenge1(orig) ByteString.from_hex(orig).to_b64 end <file_sep># Break repeating-key XOR # It is officially on, now. # # This challenge isn't conceptually hard, but it involves actual error-prone coding. The other # challenges in this set are there to bring you up to speed. This one is there to qualify you. # If you can do this one, you're probably just fine up to Set 6. # # There's a file here. It's been base64'd after being encrypted with repeating-key XOR. # # Decrypt it. # # Here's how: # # 1. # Let KEYSIZE be the guessed length of the key; try values from 2 to (say) 40. # # 2. # Write a function to compute the edit distance/Hamming distance between two strings. The Hamming # distance is just the number of differing bits. The distance between: # # this is a test # # and # # wokka wokka!!! # # is 37. Make sure your code agrees before you proceed. # # 3. # For each KEYSIZE, take the first KEYSIZE worth of bytes, and the second KEYSIZE worth of bytes, # and find the edit distance between them. Normalize this result by dividing by KEYSIZE. # # 4. # The KEYSIZE with the smallest normalized edit distance is probably the key. You could proceed # perhaps with the smallest 2-3 KEYSIZE values. Or take 4 KEYSIZE blocks instead of 2 and average the distances. # # 5. # Now that you probably know the KEYSIZE: break the ciphertext into blocks of KEYSIZE length. # # 6. # Now transpose the blocks: make a block that is the first byte of every block, and a block that # is the second byte of every block, and so on. # # 7. # Solve each block as if it was single-character XOR. You already have code to do this. # # 8. # For each block, the single-byte XOR key that produces the best looking histogram is the # repeating-key XOR key byte for that block. Put them together and you have the key. # # This code is going to turn out to be surprisingly useful later on. Breaking repeating-key XOR # ("Vigenere") statistically is obviously an academic exercise, a "Crypto 101" thing. But more # people "know how" to break it than can actually break it, and a similar technique breaks # something much more important. # # No, that's not a mistake. # We get more tech support questions for this challenge than any of the other ones. We promise, there aren't any blatant errors in this text. In particular: the "wokka wokka!!!" edit distance really is 37. require_relative 'base_utils' require_relative 'scores' $DEBUG = ENV["DBG"] def hamming_distance_for_sizes bstring, sizes_ary sizes_ary.map do |keysize| segments = 4.times.to_a.map do |segment| ByteString.new(bstring.bytes[segment*keysize, keysize]) end hammdist1 = segments[0].hamming_distance segments[1] hammdist2 = segments[1].hamming_distance segments[2] hammdist3 = segments[2].hamming_distance segments[3] hammdistavg = (hammdist1 + hammdist2 + hammdist3) / 3.0 {keysize: keysize, hammdist: hammdistavg/keysize} end.sort_by { |key| key[:hammdist] } end def best_hd_sizes hammdist_ary hammdist_ary[0..2].map { |m| m[:keysize] } end def challenge6 filename key_sizes = (2..40) file_lines = File.read(filename).lines file_lines.each { |l| l.chomp! } text = ByteString.from_b64(file_lines.join) sorted_diffs_map = hamming_distance_for_sizes(text, (2..40).to_a) potentials = best_hd_sizes sorted_diffs_map # puts "#{potentials}" toplist = [] potentials.each do |ks| printf "." unless $DEBUG == "TRUE" puts "\nTrying size #{ks}\n#{"+"*50}" if $DEBUG == "TRUE" blocks = [] index = 0 while index < text.size blocks << text.bytes[index, ks] index += ks end puts "#{blocks}" if $DEBUG == "TRUE" tblocks = ks.times.to_a.map do |i| blocks.reduce([]) { |r, b| if b[i] then r << b[i] else r end } end.map { |tb| ByteString.new tb } puts "#{tblocks}" if $DEBUG == "TRUE" ks_key = "" tblocks.map do |tb| printf "." unless $DEBUG == "TRUE" printf("\n%s\n", tb) if $DEBUG == "TRUE" score = find_best_english_score tb printf("%s\nKey: %d Score: %d\n", score[:line], score[:key], score[:score]) if $DEBUG == "TRUE" ks_key += score[:key].chr end toplist << {ks: ks, key: ks_key} end printf "\n" best = toplist.map do |t| ks = t[:ks] key = ByteString.new(t[:key].chars.map { |c| c.ord }) result = Crypto.xor_with_key text, key score = simple_score_histogram result {key: key, score: score, text: result} end .sort_by { |s| s[:score] * -1 } .first if $DEBUG == "TRUE" then puts "-" * 50 puts " " * 22 + "RESULTS" puts "-" * 50 puts "" printf "%s\n", "+" * 50 printf "++ %40s ++\n", best[:key] printf "%s\n", "+" * 50 printf "%s\n", best[:text] printf "%s\n", "+" * 50 printf "\n\n" end best[:key].to_s end <file_sep>require 'rspec' require_relative 'scores' describe "find_best_english_score" do it 'finds best key' do result = find_best_english_score ByteString.from_hex("1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736") expect(result[:key]).to eq(88) end end describe "score" do # it 'calcualtes score correctly' do # test_string = " EEEEEEEEEEEEEEEEEEEEEEEEEETTTTTTTTTTTTTTTTTTTTTTTTTAAAAAAAAAAAAAAAAAAAAAAAAOOOOOOOOOOOOOOOOOOOOOOOIIIIIIIIIIIIIIIIIIIIIINNNNNNNNNNNNNNNNNNNNNSSSSSSSSSSSSSSSSSSSSHHHHHHHHHHHHHHHHHHHRRRRRRRRRRRRRRRRRRDDDDDDDDDDDDDDDDDLLLLLLLLLLLLLLLLCCCCCCCCCCCCCCCUUUUUUUUUUUUUUMMMMMMMMMMMMMWWWWWWWWWWWWFFFFFFFFFFFGGGGGGGGGGYYYYYYYYYPPPPPPPPBBBBBBBVVVVVVKKKKKJJJJXXXQQZ" # result = simple_score_histogram test_string # expect(result.to_i).to eq(7846) # end it 'credits longer text better' do test_string1 = "TEA" test_string2 = "TEAS" result1 = simple_score_histogram test_string1 result2 = simple_score_histogram test_string2 expect(result1).to be < result2 end it 'creates frequency hash' do test_freq = {"E"=>3, "N"=>4, "C"=>3, "Y"=>2, " "=>1, "O"=>3, "B"=>2} result = freq_to_hist test_freq expect(result).to eq([["N"], ["C","E","O"], ["B","Y"], [" "]]) end end <file_sep>require_relative 'bytestring.rb' class Crypto def self.xor_with_key string, key str_bs = string key_bs = key str_index = 0 key_index = 0 results = [] while str_index < str_bs.size results << (str_bs.bytes[str_index] ^ key_bs.bytes[key_index]) str_index += 1 key_index += 1 key_index = 0 if key_index >= key_bs.size end ByteString.new(results) end end<file_sep># Fixed XOR # Write a function that takes two equal-length buffers and produces their XOR combination. # # If your function works properly, then when you feed it the string: # # 1c0111001f010100061a024b53535009181c # ... after hex decoding, and when XOR'd against: # # 686974207468652062756c6c277320657965 # ... should produce: # # 746865206b696420646f6e277420706c6179 require_relative './base_utils' def challenge2(input_str, xor_str) sin = ByteString.from_hex input_str xin = ByteString.from_hex xor_str Crypto.xor_with_key(sin, xin).to_hex end <file_sep>require_relative 'base_utils' $english_freq_order = [" ", "E", "T", "A", "O", "I", "N", "S", "H", "R", "D", "L", "C", "U", "M", "W", "F", "G", "Y", "P", "B", "V", "K", "J", "X", "Q", "Z"] def letter_frequency string freq = {} string.upcase.chars.each { |l| freq[l] = freq[l].to_i + 1 } freq end def simple_score_histogram string freq = letter_frequency string.to_s mask = $english_freq_order.dup pos_mod = 10 hist = freq_to_hist freq base_size = mask.size + 1 mask.each { |m| mask.delete m if not hist.flatten.include? m } hist.each do |set| set.each do |l| if l.ord < 32 || l.ord > 127 then pos_mod -= (base_size / 2) elsif mask.include? l then pos_mod += (base_size - mask.index(l)) end end set.each do |l| mask.delete l end end pos_mod end # def old_simple_score_histogram string # freq = letter_frequency string.to_s # mask = $english_freq_order.dup # pos_mod = 10 # hist = freq_to_hist freq # base_size = mask.size + 1 # mask.each { |m| mask.delete m if not hist.flatten.include? m } # hist.each do |set| # set.each do |l| # if mask.include? l then # pos_mod *= (((base_size - mask.index(l)) / 100.0) + 1) # end # end # set.each do |l| # mask.delete l # end # end # pos_mod # end def freq_to_hist freq_hash sorted = Hash[freq_hash.sort_by { |p| -1 * p.last }] result = [] while sorted.size > 0 f = sorted.values.first t = sorted.select { |k, v| v == f }.map { |k, v| k } t.each { |c| sorted.delete c } result << t.sort end result end def english_score input input.chars.reduce(0) do |r, c| r += 1 if (('A'..'Z').include?(c) || ('a'..'z').include?(c) || ('0'..'9').include?(c)) r += 3 if ("ETAOIN SHRDLU".include? c) r end end def find_best_english_score input_string best = (0..255) .to_a .map do |c| output = Crypto.xor_with_key input_string, c.chr possibles = {key: c, score: simple_score_histogram(output), line: output} end .sort_by { |p| -1 * p[:score] } .first # .tap do |p| # p.take(10).each do |c| # printf "(%c) %d - %s\n", c[:key], c[:score], c[:line] # end # end {score: best[:score], line: best[:line], key: best[:key] } end <file_sep># Single-byte XOR cipher # The hex encoded string: # # 1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736 # ... has been XOR'd against a single character. Find the key, decrypt the message. # # You can do this by hand. But don't: write code to do it for you. # # How? Devise some method for "scoring" a piece of English plaintext. # Character frequency is a good metric. Evaluate each output and choose # the one with the best score. require_relative './base_utils' require_relative './scores' def challenge3(input_str) score = find_best_english_score ByteString.from_hex(input_str) score[:line].to_s end<file_sep>/// Convert hex to base64 /// The string: /// /// 4<KEY>8726f6f6d /// /// Should produce: /// /// SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t /// /// So go ahead and make that happen. You'll need to use this code for the rest of the exercises. /// /// Cryptopals Rule /// Always operate on raw bytes, never on encoded strings. Only use hex and base64 for pretty-printing. use std::os; use std::fmt; static HEXMAP: &'static str = "0123456789ABCDEF"; static BASE64MAP: &'static str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; fn main() { let inp = os::args(); let hexstr = inp[1].as_slice(); let bs = ByteString::from_hex(hexstr); let result = bs.to_b64(); if hexstr == "<KEY>" { assert_eq!(result, String::from_str("SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t")); } println!("Result: {}", result) } #[deriving(PartialEq)] struct Byte { value: int, } impl Byte { fn to_hex(&self) -> (char, char) { let lv = self.value >> 4; let rv = self.value & 0b00001111; let hmap = HEXMAP.as_slice(); let lc = hmap.char_at(lv as uint); let rc = hmap.char_at(rv as uint); (lc, rc) } fn from_hex(inchar: (char, char)) -> Byte { let lc = inchar.val0().to_uppercase(); let rc = inchar.val1().to_uppercase(); let hmap = HEXMAP.as_slice(); let lv = hmap.find(lc); let rv = hmap.find(rc); let result = (lv.unwrap() << 4) + (rv.unwrap()); Byte { value: result as int } } } impl fmt::Show for Byte { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.value.fmt(f) } } #[deriving(PartialEq, Show)] struct ByteString { bytes: Vec<Byte>, } impl ByteString { fn to_hex(&self) -> String { let mut hex_string = String::new(); for b in self.bytes.iter() { let (l, r) = b.to_hex(); hex_string.push(l); hex_string.push(r); } hex_string } fn from_hex(hexstr: &str) -> ByteString { let mut result = vec!(); for pair in hexstr.as_bytes().chunks(2) { let val1:char = pair[0] as char; let val2:char = pair[1] as char; let val = Byte::from_hex((val1, val2)); result.push(val) } ByteString { bytes: result } } fn to_b64(&self) -> String { let mut result = String::new(); for trip in self.bytes.as_slice().chunks(3) { let t1 = trip[0].value; let t2 = trip[1].value; let t3 = trip[2].value; let v1 = t1 >> 2; let v2 = ((t1 & 0b00000011) << 4) + (t2 >> 4); let v3 = ((t2 & 0b00001111) << 2) + (t3 >> 6); let v4 = t3 & 0b00111111; let bmap = BASE64MAP.as_slice(); result.push(bmap.char_at(v1 as uint)); result.push(bmap.char_at(v2 as uint)); result.push(bmap.char_at(v3 as uint)); result.push(bmap.char_at(v4 as uint)); } result } } /// Automated tests /// Use 'cargo test' to run them #[test] fn test_hexmap_size() { if HEXMAP.len() != 16 { fail!("HEXMAP is the wrong size!"); } } #[test] fn test_b64map_size() { if BASE64MAP.len() != 64 { fail!("BASE64MAP is the wrong size!"); } } #[test] fn test_byte_fromhex_upcase() { let test = Byte::from_hex(('A', 'B')); if test.value != 171 { fail!("Byte::from_hex(('A', 'B')) should be value(171), not {}", test.value) } } #[test] fn test_byte_fromhex_downcase() { let test = Byte::from_hex(('a', 'b')); if test.value != 171 { fail!("Byte::from_hex(('a', 'b')) should be value(171), not {}", test.value) } } #[test] fn test_byte_fromhex_mixcase() { let test = Byte::from_hex(('A', 'b')); if test.value != 171 { fail!("Byte::from_hex(('A', 'b')) should be value(171), not {}", test.value) } } #[test] fn test_to_hex_low() { let test_val = Byte { value: 9 }; if test_val.to_hex() != ('0','9') { fail!("Byte{9}.to_hex() Should be ('0', '9')"); } } #[test] fn test_to_hex_high() { let test_val = Byte { value: 123 }; if test_val.to_hex() != ('7','B') { fail!("Byte{123}.to_hex() Should be ('7', 'B')"); } } #[test] fn test_bs_to_hex() { let a = Byte { value: 171 }; let b = Byte { value: 205 }; let c = Byte { value: 239 }; let test_bstring = ByteString {bytes: vec!(a, b, c)}; let results = test_bstring.to_hex(); if results != String::from_str("ABCDEF") { fail!("ByteString(171, 205, 239).to_hex() should be \"ABCDEF\", not {}", results); } } #[test] fn test_bs_from_hex() { let teststr = "ABC123"; let a = Byte { value: 171 }; let b = Byte { value: 193 }; let c = Byte { value: 35 }; let expected = ByteString {bytes: vec!(a, b, c)}; let results = ByteString::from_hex(teststr); if results != expected { fail!("hex 'ABC123' should result in ByteString(171, 193, 35)"); } } #[test] fn test_bs_tob64() { let a = Byte { value: 171 }; let b = Byte { value: 193 }; let c = Byte { value: 35 }; let d = Byte { value: 171 }; let e = Byte { value: 193 }; let f = Byte { value: 35 }; let test_bstring = ByteString {bytes: vec!(a, b, c, d, e, f)}; let results = test_bstring.to_b64(); if results != String::from_str("q8Ejq8Ej") { fail!("ByteString to Base64 should be \"q8Ejq8Ej\", not {}", results) } } <file_sep>require_relative 'bytestring' require_relative 'crypto'<file_sep>[package] name = "set1" version = "0.0.1" authors = ["<NAME> <<EMAIL>>"] <file_sep>require 'rspec' require_relative './challenge1' require_relative './challenge2' require_relative './challenge3' require_relative './challenge4' require_relative './challenge5' require_relative './challenge6' describe "Challenge 1" do it 'returns the correct response' do orig = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d" result = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t" expect(challenge1(orig)).to eq result end end describe "Challenge 2" do it 'returns the correct response' do input_string = "1c0111001f010100061a024b53535009181c" xor_string = "686974207468652062756c6c277320657965" result_string = "746865206b696420646f6e277420706c6179" expect(challenge2(input_string, xor_string)).to eq result_string end end describe "Challenge 3" do it 'returns the correct response' do input_string = "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736" result_string = "Cooking MC's like a pound of bacon" expect(challenge3(input_string)).to eq result_string end end describe "Challenge 4" do it 'returns the correct response' do filename = "4.txt" result_string = "Now that the party is jumping\n" expect(challenge4(filename)).to eq result_string end end describe "Challenge 5" do it 'returns the correct response' do input_string = "Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal" result_string = "0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f" expect(challenge5(input_string)).to eq result_string end end describe "Challenge 6" do it 'returns the correct key' do filename = "6.txt" key = "Terminator X: Bring the noise" expect(challenge6(filename)).to eq key end end <file_sep>These are set up to use Cargo. To run tests, run: cargo test To run the challenges, run: cargo run -c <challenge number> Note - Only the tests work at this point
3b41dcd272a5944984c5c49df8627233b8656b4c
[ "TOML", "Rust", "Ruby", "Markdown" ]
16
Ruby
RBangel/mcrypto
754ef4e1bfd099b212b23e3e56d3f90d3b383339
f3669ea51b982e293f8ac0d92c3975034aee894e
refs/heads/master
<file_sep>import numpy as np import re import random import json import collections import numpy as np #import util.parameters as params from tqdm import tqdm import nltk from nltk.corpus import wordnet as wn import os import pickle import multiprocessing as mp from itertools import islice, chain from nltk.tag import StanfordNERTagger from nltk.tag import StanfordPOSTagger from dataset import tokenize ##params #FIXED_PARAMETERS, config = params.load_parameters() nltk.download('wordnet') LABEL_MAP = { "entailment": 0, "neutral": 1, "contradiction": 2, "hidden": -1 } PADDING = "<PAD>" POS_Tagging = [PADDING, 'WP$', 'RBS', 'SYM', 'WRB', 'IN', 'VB', 'POS', 'TO', ':', '-RRB-', '$', 'MD', 'JJ', '#', 'CD', '``', 'JJR', 'NNP', "''", 'LS', 'VBP', 'VBD', 'FW', 'RBR', 'JJS', 'DT', 'VBG', 'RP', 'NNS', 'RB', 'PDT', 'PRP$', '.', 'XX', 'NNPS', 'UH', 'EX', 'NN', 'WDT', 'VBN', 'VBZ', 'CC', ',', '-LRB-', 'PRP', 'WP'] POS_dict = {pos:i for i, pos in enumerate(POS_Tagging)} stemmer = nltk.SnowballStemmer('english') tt = nltk.tokenize.treebank.TreebankWordTokenizer() def load_nli_data(path, snli=False, shuffle = True): """ Load MultiNLI or SNLI data. If the "snli" parameter is set to True, a genre label of snli will be assigned to the data. """ data = [] with open(path, encoding='utf-8') as f: for line in tqdm(f): loaded_example = json.loads(line) if loaded_example["gold_label"] not in LABEL_MAP: continue loaded_example["label"] = LABEL_MAP[loaded_example["gold_label"]] if snli: loaded_example["genre"] = "snli" data.append(loaded_example) if shuffle: random.seed(1) random.shuffle(data) return data def load_nli_data_genre(path, genre, snli=True, shuffle = True): """ Load a specific genre's examples from MultiNLI, or load SNLI data and assign a "snli" genre to the examples. If the "snli" parameter is set to True, a genre label of snli will be assigned to the data. If set to true, it will overwrite the genre label for MultiNLI data. """ data = [] j = 0 with open(path) as f: for line in f: loaded_example = json.loads(line) if loaded_example["gold_label"] not in LABEL_MAP: continue loaded_example["label"] = LABEL_MAP[loaded_example["gold_label"]] if snli: loaded_example["genre"] = "snli" if loaded_example["genre"] == genre: data.append(loaded_example) if shuffle: random.seed(1) random.shuffle(data) return data def is_exact_match(token1, token2): token1 = token1.lower() token2 = token2.lower() token1_stem = stemmer.stem(token1) if token1 == token2: return True for synsets in wn.synsets(token2): for lemma in synsets.lemma_names(): if token1_stem == stemmer.stem(lemma): return True if token1 == "n't" and token2 == "not": return True elif token1 == "not" and token2 == "n't": return True elif token1_stem == stemmer.stem(token2): return True return False def is_antonyms(token1, token2): token1 = token1.lower() token2 = token2.lower() token1_stem = stemmer.stem(token1) antonym_lists_for_token2 = [] for synsets in wn.synsets(token2): for lemma_synsets in [wn.synsets(l) for l in synsets.lemma_names()]: for lemma_syn in lemma_synsets: for lemma in lemma_syn.lemmas(): for antonym in lemma.antonyms(): antonym_lists_for_token2.append(antonym.name()) # if token1_stem == stemmer.stem(antonym.name()): # return True antonym_lists_for_token2 = list(set(antonym_lists_for_token2)) for atnm in antonym_lists_for_token2: if token1_stem == stemmer.stem(atnm): return True return False #TODO: check wordnet synonyms api def is_synonyms(token1, token2): token1 = token1.lower() token2 = token2.lower() token1_stem = stemmer.stem(token1) synonym_lists_for_token2 = [] for synsets in wn.synsets(token2): for lemma_synsets in [wn.synsets(l) for l in synsets.lemma_names()]: for lemma_syn in lemma_synsets: for lemma in lemma_syn.lemmas(): synonym_lists_for_token2.append(lemma.name()) # if token1_stem == stemmer.stem(synonym.name()): # return True synonym_lists_for_token2 = list(set(synonym_lists_for_token2)) for atnm in synonym_lists_for_token2: if token1_stem == stemmer.stem(atnm): return True return False def worker(dataset): # pat = re.compile(r'\(|\)') # def tokenize(string): # string = re.sub(pat, '', string) # return string.split() shared_content = {} for example in tqdm(dataset): s1_tokenize = tokenize(example['sentence1_binary_parse']) s2_tokenize = tokenize(example['sentence2_binary_parse']) s1_token_exact_match = [0] * len(s1_tokenize) s2_token_exact_match = [0] * len(s2_tokenize) s1_token_antonym = [0] * len(s1_tokenize) s2_token_antonym = [0] * len(s2_tokenize) s1_token_synonym = [0] * len(s1_tokenize) s2_token_synonym = [0] * len(s2_tokenize) for i, word in enumerate(s1_tokenize): matched = False for j, w2 in enumerate(s2_tokenize): matched = is_exact_match(word, w2) if matched: s1_token_exact_match[i] = 1 s2_token_exact_match[j] = 1 ant = is_antonyms(word, w2) if ant: s1_token_antonym[i] = 1 s2_token_antonym[j] = 1 syn = is_synonyms(word,w2) if syn: s1_token_synonym[i] = 1 s2_token_synonym[j] = 1 #TODO: add synonym content = {} content['sentence1_token_exact_match_with_s2'] = s1_token_exact_match content['sentence2_token_exact_match_with_s1'] = s2_token_exact_match content['sentence1_token_antonym_with_s2'] = s1_token_antonym content['sentence2_token_antonym_with_s1'] = s2_token_antonym content['sentence1_token_synonym_with_s2'] = s1_token_synonym content['sentence2_token_synonym_with_s1'] = s2_token_synonym #TODO: syn content shared_content[example["pairID"]] = content # print(shared_content[example["pairID"]]) # print(shared_content) return shared_content def partition(x, n): return ([i for i in islice(x,j,j+n)] for j in range(0,len(x),n)) shared_files = [ "DIIN/data/multinli_0.9/shared_dev_matched.json", "DIIN/data/multinli_0.9/shared_dev_mismatched.json", "DIIN/data/multinli_0.9/shared_train.json", ] data_files = [ "./DIIN/data/multinli_0.9/multinli_0.9_dev_matched.jsonl", "./DIIN/data/multinli_0.9/multinli_0.9_dev_mismatched.jsonl", "./DIIN/data/multinli_0.9/multinli_0.9_train.jsonl", ] fsize = [500, 500, 10000] p = mp.Pool(8) for sf, df, fs in zip(shared_files, data_files, fsize): print(f"processing {df}...") dataset = load_nli_data(df) shared = {k:v for d in p.map(worker, partition(dataset, fs)) for k,v in d.items()} with open(sf, "w") as f: for k in shared: f.write(f"{k} {json.dumps(shared[k])}\n") print("done") # dataset = load_nli_data("./DIIN/data/multinli_0.9/multinli_0.9_train.jsonl")#TODO: path # p = mp.Pool(10) # shared = {k:v for d in p.map(worker, partition(dataset, 10000)) for k,v in d.items()} # #save to file # #TODO: # with open("./DIIN/data/multinli_0.9/shared.json", "w") as f: # for k in shared: # f.write(f"{k} {json.dumps(shared[k])}") <file_sep>import json import gzip import time import os import io import re import subprocess as sp import string import pdb import tensorflow as tf import numpy as np import nltk from tqdm import tqdm from util.util import tprint, group2 DEFAULT_LABEL2IDX = {'neutral': 0, 'entailment': 1, 'contradiction': 2, 'hidden': 3, '-': -1} DEFAULT_WORD2IDX = {"<PAD>":0, "<UNK>":1} DEFAULT_CHAR2IDX = {c:i for i, c in enumerate(string.printable)} DEFAULT_CHAR2IDX['\0'] = 0 DEFAULT_CHARPAD = 16 POS_Tagging = ['<PAD>', '<UNK>', 'WP$', 'RBS', 'SYM', 'WRB', 'IN', 'VB', 'POS', 'TO', ':', '-RRB-', '$', 'MD', 'JJ', '#', 'CD', '``', 'JJR', 'NNP', "''", 'LS', 'VBP', 'VBD', 'FW', 'RBR', 'JJS', 'DT', 'VBG', 'RP', 'NNS', 'RB', 'PDT', 'PRP$', '.', 'XX', 'NNPS', 'UH', 'EX', 'NN', 'WDT', 'VBN', 'VBZ', 'CC', ',', '-LRB-', 'PRP', 'WP'] POS2IDX = {pos:i for i, pos in enumerate(POS_Tagging)} shared_files = ["../data/multinli_0.9/shared_train.json", "../data/multinli_0.9/shared_dev_matched.json", "../data/multinli_0.9/shared_dev_mismatched.json", ] def load_shared_content(): tprint("loading shared_files") shared_content = {} for sf in shared_files: with open(sf, "r") as sfd: for l in tqdm(sfd): pairID = l.split(" ")[0] shared_content[pairID] = json.loads(l[len(pairID)+1:]) return shared_content def label2index(x, l2i=DEFAULT_LABEL2IDX): return l2i[x] def word2index(x, w2i=DEFAULT_WORD2IDX): return w2i.get(x, w2i['<UNK>']) def char2index(x, c2i=DEFAULT_CHAR2IDX, pad=DEFAULT_CHARPAD): cm = [c2i.get(c, c2i['\0']) for c in x] if len(x) > pad: return np.array(cm[:pad]) else: return np.array(cm + [0] * (pad - len(x))) def pos2index(x): global POS2IDX return POS2IDX.get(x, POS2IDX['<UNK>']) def extract_json(x, key): d = json.loads(x.decode("utf-8")) return d[key] pat = re.compile(r'\(|\)') def _tokenize(string): global pat string = re.sub(pat, '', string) return filter(None, string.split(" ")) def tokenize(s, func=lambda x: x): return [func(t) for t in _tokenize(s)] def parse_pos(s, func=lambda x: x): posp = (x.rstrip(" ").rstrip(")") for x in s.split("(") if ")" in x) pos = [func(p.split(" ")[0]) for p in posp] return pos def random_embedding(size, dim, keep_zeros=[]): emb = np.random.randn(size, dim) for i in keep_zeros: emb[i] = np.zeros(dim) return emb def count_word(zfile, size=None): tprint("loadding glove") word2idx = {"<PAD>":0, "<UNK>":1} embedding = [np.zeros(300), np.zeros(300), ] with io.BufferedReader(gzip.open(zfile, "rb")) as f: for i, l in tqdm(enumerate(f)): l = l.decode("utf-8") values = l.split(" ") w = values.pop(0) word2idx[w] = i+2 embedding.append(np.asarray(values, dtype=np.float32)) if size and i+2 >= size - 1: break embedding = np.array(embedding) return word2idx, embedding def count_char(path): tprint("counting char") chars = set() with open(path, "r") as f: for i, l in tqdm(enumerate(f)): j = json.loads(l) chars |= set(j["sentence1"]) chars |= set(j["sentence2"]) char2idx = {c:i+1 for i, c in enumerate(chars)} char2idx['\0'] = 0 return char2idx def resize(x, size): x.set_shape(size) return x def padding(x, y, left=False): xsa = tf.shape(x) ysa = tf.shape(y) xr = len(x.get_shape()) yr = len(y.get_shape()) xs = xsa[1] ys = ysa[1] sm = tf.maximum(xs,ys) xp = tf.abs(xs - sm) yp = tf.abs(ys - sm) xpad = np.zeros((xr,2), dtype=np.int64).tolist() ypad = np.zeros((yr,2), dtype=np.int64).tolist() if left: xpad[1][0] = xp ypad[1][0] = yp else: xpad[1][1] = xp ypad[1][1] = yp return tf.pad(x, xpad), tf.pad(y, ypad) def crop(x, max_len): xr = len(x.get_shape()) xl = tf.shape(x)[1] if xr == 2: return tf.cond(xl <= max_len, lambda: x, lambda: x[:,:max_len]) elif xr == 3: return tf.cond(xl <= max_len, lambda: x, lambda: x[:,:max_len, :]) else: raise Exception("cropping rank not support") def MapDatasetJSON(dataset, key, dtype=None, osize=(), func=lambda x: x): if not dtype: raise ValueError("output type not specified.") if isinstance(dtype, list) or isinstance(dtype, tuple): assert isinstance(osize, list) or isinstance(osize, tuple) _func = (lambda x: [func(extract_json(x, key))]) \ if isinstance(dtype, list) or isinstance(dtype, tuple) \ else (lambda x: func(extract_json(x, key))) return dataset.map( lambda line: tf.py_func( _func, [line], dtype) ).map(lambda x: resize(x, osize)) def MapDatasetString(dataset, key, osize=[None], dtype=[tf.string], tkn=tokenize, func=lambda x: x): return MapDatasetJSON(dataset, key, dtype=dtype, osize=osize, func=lambda x: tkn(x, func=func)) def MNLIJSONDataset(filename, batch=10, epoch=1, shuffle_buffer_size=1, word2index=word2index, char2index=char2index, char_pad=DEFAULT_CHARPAD, max_len=None, sc=None, pad2=True): names = [] values = [] dataset = tf.data.TextLineDataset(filename) names.append("label") gold_label = MapDatasetJSON(dataset, "gold_label", dtype=tf.int64, func=label2index).repeat(epoch).batch(batch) values.append(gold_label) names.append("sentence1") sentence1 = MapDatasetString(dataset, "sentence1_binary_parse", dtype=[tf.int64], func=word2index).repeat(epoch).padded_batch(batch, [None]) values.append(sentence1) names.append("sentence2") sentence2 = MapDatasetString(dataset, "sentence2_binary_parse", dtype=[tf.int64], func=word2index).repeat(epoch).padded_batch(batch, [None]) values.append(sentence2) ###20180629 char_embedding names.append("sent1char") sent1_char = MapDatasetString(dataset, "sentence1_binary_parse", osize=[None, char_pad], dtype=[tf.int64], func=char2index).repeat(epoch).padded_batch(batch, [None, char_pad]) values.append(sent1_char) names.append("sent2char") sent2_char = MapDatasetString(dataset, "sentence2_binary_parse", osize=[None, char_pad], dtype=[tf.int64], func=char2index).repeat(epoch).padded_batch(batch, [None, char_pad]) values.append(sent2_char) names.append("antonym1") antonym1 = MapDatasetJSON(dataset, "pairID", dtype=[tf.float32], osize=[None], func=lambda x: np.array(sc[x]["sentence1_token_antonym_with_s2"]).astype(np.float32)).repeat(epoch).padded_batch(batch, [None]) values.append(antonym1) names.append("antonym2") antonym2 = MapDatasetJSON(dataset, "pairID", dtype=[tf.float32], osize=[None], func=lambda x: np.array(sc[x]["sentence2_token_antonym_with_s1"]).astype(np.float32)).repeat(epoch).padded_batch(batch, [None]) values.append(antonym2) names.append("exact1to2") exact1to2 = MapDatasetJSON(dataset, "pairID", dtype=[tf.float32], osize=[None], func=lambda x: np.array(sc[x]["sentence1_token_exact_match_with_s2"]).astype(np.float32)).repeat(epoch).padded_batch(batch, [None]) values.append(exact1to2) names.append("exact2to1") exact2to1 = MapDatasetJSON(dataset, "pairID", dtype=[tf.float32], osize=[None], func=lambda x: np.array(sc[x]["sentence2_token_exact_match_with_s1"]).astype(np.float32)).repeat(epoch).padded_batch(batch, [None]) values.append(exact2to1) names.append("synonym1") synonym1 = MapDatasetJSON(dataset, "pairID", dtype=[tf.float32], osize=[None], func=lambda x: np.array(sc[x]["sentence1_token_synonym_with_s2"]).astype(np.float32)).repeat(epoch).padded_batch(batch, [None]) values.append(synonym1) names.append("synonym2") synonym2 = MapDatasetJSON(dataset, "pairID", dtype=[tf.float32], osize=[None], func=lambda x: np.array(sc[x]["sentence2_token_synonym_with_s1"]).astype(np.float32)).repeat(epoch).padded_batch(batch, [None]) values.append(synonym2) names.append("pos1") pos1 = MapDatasetString(dataset, "sentence1_parse", dtype=[tf.int64], tkn=parse_pos, func=pos2index).repeat(epoch).padded_batch(batch, [None]) values.append(pos1) names.append("pos2") pos2 = MapDatasetString(dataset, "sentence2_parse", dtype=[tf.int64], tkn=parse_pos, func=pos2index).repeat(epoch).padded_batch(batch, [None]) values.append(pos2) D = tf.data.Dataset.zip(tuple(values)) if pad2: D = D.map(lambda l, *arg: (l, *(v for t in map(lambda x: padding(*x), group2(arg)) for v in t))) if max_len: D = D.map(lambda l, *arg: (l, *map(lambda x: crop(x, max_len), arg))) D = D.map(lambda *val: {n:v for n, v in zip(names, val)}) return D.shuffle(shuffle_buffer_size) def MnliTrainSet(filename="multinli_0.9_train.jsonl", batch=10, epoch=1, shuffle_buffer_size=1, prefetch_buffer_size=1, w2i=word2index, c2i=char2index, char_pad=DEFAULT_CHARPAD, max_len=None, sc=None, pad2=True): train = MNLIJSONDataset(filename, batch, epoch, shuffle_buffer_size, word2index=w2i, pad2=pad2, char_pad=char_pad, max_len=max_len, sc=sc ) return train.prefetch(prefetch_buffer_size) def MnliDevSet(files=("multinli_0.9_dev_mismatched_clean.jsonl", "multinli_0.9_dev_matched_clean.jsonl"), batch=10, epoch=1, shuffle_buffer_size=1, prefetch_buffer_size=1, w2i=word2index, c2i=char2index, char_pad=DEFAULT_CHARPAD, max_len = None, sc=None, pad2=True): dev_mismatch = MNLIJSONDataset(files[0], batch, epoch, shuffle_buffer_size, w2i, pad2=pad2, char_pad=char_pad, max_len=max_len, sc=sc ) dev_match = MNLIJSONDataset(files[1], batch, epoch, shuffle_buffer_size, w2i, pad2=pad2, char_pad=char_pad, max_len=max_len, sc=sc ) return {"match": dev_match.prefetch(prefetch_buffer_size), "mismatch": dev_mismatch.prefetch(prefetch_buffer_size)} #return dev_match.concatenate(dev_mismatch).prefetch(prefetch_buffer_size) def Mnli(tfile="multinli_0.9_train.jsonl", dfiles=("multinli_0.9_dev_mismatched_clean.jsonl", "multinli_0.9_dev_matched_clean.jsonl"), tbatch=10, dbatch=5, tepoch=5, depoch=1, shuffle_buffer_size=20, prefetch_buffer_size=3, w2i=word2index, c2i=char2index, char_pad=DEFAULT_CHARPAD, max_len=None, sc=None, pad2=True): trainset = MnliTrainSet(tfile, batch=tbatch, epoch=tepoch, shuffle_buffer_size=shuffle_buffer_size, prefetch_buffer_size=prefetch_buffer_size, w2i=w2i, c2i=c2i, char_pad=char_pad, max_len=max_len, sc=sc, pad2=pad2) devset = MnliDevSet(dfiles, batch=dbatch, epoch=depoch, shuffle_buffer_size=shuffle_buffer_size, prefetch_buffer_size=prefetch_buffer_size, w2i=w2i, c2i=c2i, char_pad=char_pad, max_len=max_len, sc=sc, pad2=pad2) iterator = tf.data.Iterator.from_structure(trainset.output_types, trainset.output_shapes) train_init = iterator.make_initializer(trainset) dev_match_init = iterator.make_initializer(devset["match"]) dev_mismatch_init = iterator.make_initializer(devset["mismatch"]) Next = iterator.get_next() return Next, {"train": train_init, "dev_match": dev_match_init, "dev_mismatch": dev_mismatch_init} class MultiNli: def __init__(self, glove_path, mnli_path, batch=5, train_epoch=10, dev_epoch=1, shuffle_buffer_size=10, prefetch_buffer_size=1, glove_size=None, pad2=True, trainfile=None, all_printable_char=False, char_emb_dim=100, char_pad=DEFAULT_CHARPAD, max_len=None, ): self.glove_path = glove_path self.glove_size = glove_size self.mnli_path = mnli_path self.batch = batch self.train_epoch = train_epoch self.dev_epoch = dev_epoch self.shuffle_buffer_size = shuffle_buffer_size self.prefetch_buffer_size = prefetch_buffer_size self.pad2 = pad2 self.max_len = max_len self.char_pad = char_pad self.char_emb_dim = char_emb_dim self.trainfile = os.path.join(mnli_path, "multinli_0.9_train.jsonl") if not trainfile else os.path.join(mnli_path, trainfile) self.devfile = tuple(os.path.join(mnli_path, dfile) for dfile in ("multinli_0.9_dev_mismatched_clean.jsonl", "multinli_0.9_dev_matched_clean.jsonl")) self.train_size = int(sp.check_output(["wc", "-l", self.trainfile]).split()[0]) self.dev_size = [int(sp.check_output(["wc", "-l", devf]).split()[0]) for devf in self.devfile] #load shared_content self.shared_content = load_shared_content() #load word embedding self.word2idx, self.embedding = count_word(self.glove_path, self.glove_size) #load char embedding if all_printable_char: self.char2idx = DEFAULT_CHAR2IDX else: self.char2idx = count_char(self.trainfile) #gen random char emb self.char_embedding = random_embedding(len(self.char2idx), self.char_emb_dim, keep_zeros=(0,)) #gen random pos emb global POS2IDX self.pos2idx = POS2IDX self.pos_embedding = random_embedding(len(self.pos2idx), len(self.pos2idx), keep_zeros=(0,)) #setup dataset self.data, self.init = Mnli(tfile=self.trainfile, dfiles=self.devfile, tbatch=self.batch, dbatch=self.batch, tepoch=self.train_epoch, depoch=self.dev_epoch, shuffle_buffer_size=self.shuffle_buffer_size, prefetch_buffer_size=self.prefetch_buffer_size, w2i=lambda x: word2index(x, self.word2idx), pad2=self.pad2, c2i=lambda x: char2index(x, self.char2idx, pad=self.char_pad), max_len=self.max_len, sc=self.shared_content ) def __getattr__(self, name): prop = self.data.get(name, None) if not prop is None: return prop else: self.__getattribute__(name) def train(self, sess): sess.run(self.init['train']) def dev_matched(self, sess): sess.run(self.init['dev_match']) def dev_mismatched(self, sess): sess.run(self.init['dev_mismatch']) def get_batch(self): return self.data <file_sep>import time def timef(): return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) def tprint(msg): print(timef(), end=": ") print(msg) def group2(x): for i in range(0,len(x),2): if i+1 >= len(x): yield (x[i],) else: yield (x[i], x[i+1]) <file_sep>import tensorflow as tf def ZeroPadEmbeddingWeight(weights, name="", trainable=True): vs, dims = weights.shape weight_init = tf.constant_initializer(weights[1:, :]) embedding_weights = tf.get_variable( name=f'{name + "_" if name else ""}embedding_weights', shape=(vs-1, dims), initializer=weight_init, trainable=trainable) zeropad = tf.zeros((1,dims), dtype=tf.float32) return tf.concat((zeropad, embedding_weights), 0) def embedded(weights, name="", trainable=True, mask_padding=True): if mask_padding: embedding_weights = ZeroPadEmbeddingWeight(weights, name=name, trainable=trainable) else: weight_init = tf.constant_initializer(weights) embedding_weights = tf.get_variable( name = f'{name + "_" if name else ""}embedding_weights', shape = weights.shape, initializer = weight_init, trainable = trainable) def lookup(x): nonlocal embedding_weights return tf.nn.embedding_lookup(embedding_weights, x) return lookup def char_conv(inp, filter_size=5, channel_out=100, strides=[1, 1, 1, 1], padding="SAME", dilations=[1, 1, 1, 1]): inc = inp.get_shape().as_list()[-1] filts = tf.get_variable("char_filter", shape=(1, filter_size, inc, channel_out), dtype=tf.float32) bias = tf.get_variable("char_bias", shape=(channel_out,), dtype=tf.float32) conv = tf.nn.conv2d(inp, filts, strides=strides, padding=padding, dilations=dilations) + bias out = tf.reduce_max(tf.nn.relu(conv), 2) return out def mask(x, x_mask=None): if x_mask is None: return x dim = x.get_shape().as_list()[-1] mask = tf.tile(tf.expand_dims(x_mask, -1), [1, 1, dim]) return x * mask def normalize(inputs, epsilon=1e-8, scope="ln", reuse=None): '''Applies layer normalization. Args: inputs: A tensor with 2 or more dimensions, where the first dimension has `batch_size`. epsilon: A floating number. A very small number for preventing ZeroDivision Error. scope: Optional scope for `variable_scope`. reuse: Boolean, whether to reuse the weights of a previous layer by the same name. Returns: A tensor with the same shape and data dtype as `inputs`. ''' with tf.variable_scope(scope, reuse=reuse): inputs_shape = inputs.get_shape() params_shape = inputs_shape[-1:] mean, variance = tf.nn.moments(inputs, [-1], keep_dims=True) beta = tf.Variable(tf.zeros(params_shape)) gamma = tf.Variable(tf.ones(params_shape)) normalized = (inputs - mean) / ((variance + epsilon) ** (.5)) outputs = gamma * normalized + beta return outputs def highway(x, activation): size = x.get_shape().as_list()[-1] W = tf.get_variable("W", (size, size), initializer=tf.random_normal_initializer()) b = tf.get_variable("b", size, initializer=tf.constant_initializer(0.0)) Wt = tf.get_variable("Wt", (size, size), initializer=tf.random_normal_initializer()) bt = tf.get_variable("bt", size, initializer=tf.constant_initializer(0.0)) T = tf.sigmoid(tf.tensordot(x, Wt, 1) + bt, name="transform_gate") H = activation(tf.tensordot(x, W, 1) + b, name="activation") C = tf.subtract(1.0, T, name="carry_gate") y = tf.add(tf.multiply(H, T), tf.multiply(x, C), "y") return y def highway_network(x, num, activation, name, reuse=None): for i, a in zip(range(num), activation): with tf.variable_scope(f"{name}_highway{i+1}", reuse=reuse): x = highway(x, a) return x def attention(q, k): #q: [B, ql, d], k: [B, kl, d] ql = tf.shape(q)[1] kl = tf.shape(k)[1] qs = tf.tile(tf.expand_dims(q, 2), [1, 1, kl, 1]) #[B, ql, kl, d] ks = tf.tile(tf.expand_dims(k, 1), [1, ql, 1, 1]) #[B, ql, kl, d] qk = qs * ks h = tf.concat([qs, ks, qk], -1) e = tf.squeeze(tf.layers.dense(h, 1), -1) # [B, ql, kl] a = tf.nn.softmax(e, -1) v = tf.matmul(a, k) #[B, ql, d] return v def ffn(x, d, act=None): a = tf.layers.dense(x, d, activation=act) return tf.layers.dense(a, d) def pwffn(x, ff=2048): dim = x.get_shape().as_list()[-1] a = tf.layers.dense(x, ff, activation=tf.nn.relu) return tf.layers.dense(a, dim) def multihead_attention(q, k, v, dk=64, h = 8, ff=2048, scope="multihead_attention", reuse=None): with tf.variable_scope(scope, reuse=reuse): dim = q.get_shape().as_list()[-1] b = tf.shape(q)[0] ql = tf.shape(q)[1] kl = tf.shape(k)[1] vl = kl Q = tf.layers.dense(q, h*dk) K = tf.layers.dense(k, h*dk) V = tf.layers.dense(v, h*dk) hq = tf.reshape(Q, (b*h, ql, dk)) hk = tf.reshape(K, (b*h, kl, dk)) hv = tf.reshape(V, (b*h, vl, dk)) #[b*h, vl, dk] qkt = tf.matmul(hq, tf.transpose(hk, (0, 2, 1))) / (dk ** 0.5)#[b*h, ql, kl=vl] a = tf.nn.softmax(qkt, -1) hatten = tf.matmul(a , hv) #[b*h, ql, dk] hatten = tf.reshape(hatten, (b, ql, h*dk)) atten = tf.layers.dense(hatten, dim, use_bias=False) aoutput = normalize(atten + q) output = pwffn(aoutput, ff) output = normalize(aoutput + output) return output <file_sep>import os from time import time import tensorflow as tf import numpy as np from tqdm import tqdm parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) os.sys.path.insert(0, parentdir) from .nn import embedded, mask, highway_network, multihead_attention, normalize, char_conv, ffn from util.util import tprint os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' class EntailModel: def __init__(self, name, hidden_dim, num_heads, filter_size, dataset, learning_rate=0.000005, model_path="../../model/", retrain=True, char=True, pos=True, use_placeholder=False, dropout=False, keep_rate= 0.9, l2=True, clip=True, clip_value=1.0, ): self.name = name self.hidden_dim = hidden_dim self.num_heads = num_heads self.filter_size = filter_size self.dataset = dataset self.learning_rate = learning_rate self.model_path = model_path self.retrain = retrain self.char = char self.pos = pos self.use_placeholder = use_placeholder self.dropout = dropout self.keep_rate_value = keep_rate self.l2 = l2 self.clip = clip self.clip_value = clip_value def dataprovider(self): if not self.use_placeholder: #sentence self.sentence1 = self.dataset.sentence1 self.sentence2 = self.dataset.sentence2 #labels self.labels = self.dataset.label #preprocess info self.antonym1 = tf.expand_dims(self.dataset.antonym1, -1) self.antonym2 = tf.expand_dims(self.dataset.antonym2, -1) self.exact1to2 = tf.expand_dims(self.dataset.exact1to2, -1) self.exact2to1 = tf.expand_dims(self.dataset.exact2to1, -1) self.synonym1 = tf.expand_dims(self.dataset.synonym1, -1) self.synonym2 = tf.expand_dims(self.dataset.synonym2, -1) #pos if self.pos: self.pos1 = self.dataset.pos1 self.pos2 = self.dataset.pos2 #char if self.char: self.sent1char = self.dataset.sent1char self.sent2char = self.dataset.sent2char else: #sentence self.sentence1 = tf.placeholder(tf.int64, shape=[None, None], name="premise") self.sentence2 = tf.placeholder(tf.int64, shape=[None, None], name="hypothesis") ###labels self.labels = tf.placeholder(tf.int64, shape=[None], name="label") #preprocess info self.antonym1 = tf.expand_dims(tf.placeholder(tf.float32, shape=[None, None], name="antonym1"), -1) self.antonym2 = tf.expand_dims(tf.placeholder(tf.float32, shape=[None, None], name="antonym2"), -1) self.exact1to2 = tf.expand_dims(tf.placeholder(tf.float32, shape=[None, None], name="exact1to2"), -1) self.exact2to1 = tf.expand_dims(tf.placeholder(tf.float32, shape=[None, None], name="exact2to1"), -1) self.synonym1 = tf.expand_dims(tf.placeholder(tf.float32, shape=[None, None], name="synonym1"), -1) self.synonym2 = tf.expand_dims(tf.placeholder(tf.float32, shape=[None, None], name="synonym2"), -1) #pos if self.pos: self.pos1 = tf.placeholder(tf.int64, shape=[None, None], name="pos1") self.pos2 = tf.placeholder(tf.int64, shape=[None, None], name="pos2") #char if self.char: self.sent1char = tf.placeholder(tf.int64, shape=[None, None, self.dataset.char_pad], name="sent1char") self.sent2char = tf.placeholder(tf.int64, shape=[None, None, self.dataset.char_pad], name="sent2char") #masks self.sent1_mask = tf.cast(tf.sign(self.sentence1), dtype=tf.float32) self.sent2_mask = tf.cast(tf.sign(self.sentence2), dtype=tf.float32) self.sent1_len = tf.reduce_sum(self.sent1_mask, -1) self.sent2_len = tf.reduce_sum(self.sent2_mask, -1) #dropout self.keep_rate = tf.placeholder_with_default(tf.constant(self.keep_rate_value), shape=(), name="keep_rate" ) def word_embedding(self): with tf.variable_scope("word_embedding"): self.glove_embedding = embedded(self.dataset.embedding) self.embedding_pre = self.glove_embedding(self.sentence1) self.embedding_hyp = self.glove_embedding(self.sentence2) if self.dropout: self.embedding_pre = tf.nn.dropout(self.embedding_pre, self.keep_rate) self.embedding_hyp = tf.nn.dropout(self.embedding_hyp, self.keep_rate) def char_embedding(self): with tf.variable_scope("char_embedding"): self.char_embedding = embedded(self.dataset.char_embedding, name="char") self.char_embedding_pre = self.char_embedding(self.sent1char) self.char_embedding_hyp = self.char_embedding(self.sent2char) with tf.variable_scope("conv") as scope: self.conv_pre = char_conv(self.char_embedding_pre, filter_size=self.filter_size) scope.reuse_variables() self.conv_hyp = char_conv(self.char_embedding_hyp, filter_size=self.filter_size) if self.dropout: self.conv_pre = tf.nn.dropout(self.conv_pre, self.keep_rate) self.conv_hyp = tf.nn.dropout(self.conv_hyp, self.keep_rate) def pos_embedding(self): with tf.variable_scope("pos_embedding"): self.pos_embedding = embedded(self.dataset.pos_embedding, name="pos") self.pos_embedding_pre = self.pos_embedding(self.pos1) self.pos_embedding_hyp = self.pos_embedding(self.pos2) if self.dropout: self.pos_embedding_pre = tf.nn.dropout(self.pos_embedding_pre, self.keep_rate) self.pos_embedding_hyp = tf.nn.dropout(self.pos_embedding_hyp, self.keep_rate) def embedding(self): tprint("building embedding") self.word_embedding() s1_e = [self.embedding_pre, self.antonym1, self.exact1to2, self.synonym1] s2_e = [self.embedding_hyp, self.antonym2, self.exact2to1, self.synonym2] if self.char: self.char_embedding() s1_e.append(self.conv_pre) s2_e.append(self.conv_hyp) if self.pos: self.pos_embedding() s1_e.append(self.pos_embedding_pre) s2_e.append(self.pos_embedding_hyp) self.embed_pre = tf.concat(s1_e, -1) self.embed_hyp = tf.concat(s2_e, -1) def encoding(self): tprint("building highway encoder") self.hout_pre = highway_network(self.embed_pre, 2, [tf.nn.sigmoid] * 2, "premise") self.hout_hyp = highway_network(self.embed_hyp, 2, [tf.nn.sigmoid] * 2, "hypothesis") #dim reduction self.hout_pre = normalize(tf.layers.dense(self.hout_pre, self.hidden_dim, activation=tf.nn.sigmoid)) self.hout_hyp = normalize(tf.layers.dense(self.hout_hyp, self.hidden_dim, activation=tf.nn.sigmoid)) if self.dropout: self.hout_pre = tf.nn.dropout(self.hout_pre, self.keep_rate) self.hout_hyp = tf.nn.dropout(self.hout_hyp, self.keep_rate) self.hout_pre = mask(self.hout_pre, self.sent1_mask) self.hout_hyp = mask(self.hout_hyp, self.sent2_mask) def attention(self): tprint("build attention") self.pre_atten = multihead_attention(self.hout_pre, self.hout_pre, self.hout_pre, h = self.num_heads, scope="pre_atten" ) self.hyp_atten = multihead_attention(self.hout_hyp, self.hout_hyp, self.hout_hyp, h = self.num_heads, scope="hyp_atten" ) self.p2h_atten = multihead_attention(self.pre_atten, self.hyp_atten, self.hyp_atten, h = self.num_heads, scope="p2h_atten" ) self.h2p_atten = multihead_attention(self.hyp_atten, self.pre_atten, self.pre_atten, h = self.num_heads, scope="h2p_atten" ) def _align_aggregate(self, s, a): concat = tf.concat((s,a), -1) mul = s * a sub = s - a return tf.concat((concat, mul, sub), -1) def attention_integration(self): tprint("build attention integration") self.P_ = ffn(self._align_aggregate(self.hout_pre, self.pre_atten), self.hidden_dim, act=tf.nn.tanh) self.H_ = ffn(self._align_aggregate(self.hout_hyp, self.hyp_atten), self.hidden_dim, act=tf.nn.tanh) self.P_ = mask(self.P_, self.sent1_mask) self.H_ = mask(self.H_, self.sent2_mask) self.PH_ = ffn(self._align_aggregate(self.hout_pre, self.p2h_atten), self.hidden_dim, act=tf.nn.tanh) self.HP_ = ffn(self._align_aggregate(self.hout_hyp, self.h2p_atten), self.hidden_dim, act=tf.nn.tanh) self.PH_ = mask(self.PH_, self.sent1_mask) self.HP_ = mask(self.HP_, self.sent2_mask) self.P = tf.concat([self.P_, self.PH_], -1) self.H = tf.concat([self.H_, self.HP_], -1) if self.dropout: self.P = tf.nn.dropout(self.P, self.keep_rate) self.H = tf.nn.dropout(self.H, self.keep_rate) def interaction(self): tprint("build rnn") self.rnn_cell = tf.nn.rnn_cell.GRUCell(num_units=self.hidden_dim) self.p_outputs, self.p_state = tf.nn.dynamic_rnn(self.rnn_cell, self.P, sequence_length=self.sent1_len, dtype=tf.float32) self.h_outputs, self.h_state = tf.nn.dynamic_rnn(self.rnn_cell, self.H, sequence_length=self.sent2_len, initial_state=self.p_state, dtype=tf.float32) self.ph = tf.concat((self.p_state, self.h_state), 1) def classify(self): tprint("build classifier") self.clf = highway_network(self.ph, 3, [tf.nn.sigmoid] * 3, "clf") self.y = tf.layers.dense(self.clf, 3) def loss(self): tprint("build loss") self.loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(labels=self.labels, logits=self.y)) if self.l2: l2_loss = tf.add_n([tf.nn.l2_loss(v) for v in tf.trainable_variables()]) self.loss += l2_loss * 9e-5 def optimizer(self): self.optimizer = tf.train.AdamOptimizer(self.learning_rate) if self.clip: self.tvars = tf.trainable_variables() grads, _ = tf.clip_by_global_norm(tf.gradients(self.loss, self.tvars), self.clip_value) self.train_op = self.optimizer.apply_gradients(zip(grads, self.tvars)) else: self.train_op = self.optimizer.minimize(loss) def metrics(self): self.predictlabel = tf.argmax(self.y, axis=1) self.correctlabel = tf.cast(tf.equal(self.predictlabel, self.labels), dtype=tf.float32) self.correctnumber = tf.reduce_sum(self.correctlabel) self.correctPred = tf.reduce_mean(self.correctlabel) def initialize(self): tprint("initializing") self.saver = tf.train.Saver() sess_config = tf.ConfigProto() sess_config.gpu_options.allow_growth = True self.sess = tf.Session(config=sess_config) if self.retrain: init = tf.global_variables_initializer() self.sess.run(init) else: self.saver.restore(self.sess, os.path.join(self.model_path, self.name)) tprint("done") def build(self): tprint("building graph") BST = time() self.dataprovider() self.embedding() self.encoding() self.attention() self.attention_integration() self.interaction() self.classify() self.loss() self.optimizer() self.metrics() tprint(f"finish build graph. take {time()-BST} seconds.") self.para_num = sum([np.prod(v.get_shape()) for v in self.tvars]).value tprint(f"parameters num: {self.para_num}") self.initialize() def _set_feed_dict(self, feed_dict, samples): feed_dict["premise:0"] = [j["sentence1"] for j in samples] feed_dict["hypothesis:0"] = [j["sentence2"] for j in samples] feed_dict["labels:0"] = [j["label"] for j in samples] feed_dict["antonym1:0"] = [j["antonym11"] for j in samples] feed_dict["antonym2:0"] = [j["antonym2"] for j in samples] feed_dict["exact1to2:0"] = [j["exact1to2"] for j in samples] feed_dict["exact2to1:0"] = [j["exact2to1"] for j in samples] feed_dict["synonym1:0"] = [j["synonym1"] for j in samples] feed_dict["synonym2:0"] = [j["synonym2"] for j in samples] #pos if self.pos: feed_dict["pos1:0"] = [j["pos1"] for j in samples] feed_dict["pos2:0"] = [j["pos2"] for j in samples] #char if self.char: feed_dict["sent1char:0"] = [j["sent1char"] for j in samples] feed_dict["sent2char:0"] = [j["sent2char"] for j in samples] return feed_dict def run(self, init=None, e=1, train=False, name="", printnum=500): for epoch in range(e): total_loss = 0. batch_number = 0 total_pred = 0. # total_pred for one epoch local_pred = 0. local_loss = 0. # init_trainset if not self.use_placeholder: init(self.sess) while True: try: feed_dict = {} if train: run_op = (self.train_op, self.loss, self.correctPred) else: run_op = (self.loss, self.correctPred) feed_dict[self.keep_rate] = 1.0 if self.use_placeholder: samples = self.dataset.get_minibatch() feed_dict = self._set_feed_dict(feed_dict, samples) *_, loss_value, pred = self.sess.run(run_op, feed_dict) total_loss += loss_value local_loss += loss_value total_pred += pred local_pred += pred batch_number += 1 if batch_number % printnum == 0: tprint(f"{name}> average_loss:{local_loss/printnum}, local_accuracy:{local_pred/printnum}") local_pred = 0. local_loss = 0. except tf.errors.OutOfRangeError: break tprint(f"{name}> total_loss:{total_loss/batch_number}, total_accuracy:{total_pred/batch_number}" ) <file_sep>import os from time import time import tensorflow as tf import numpy as np from tqdm import tqdm from dataset import MultiNli from util.util import tprint from model.model import EntailModel ######parameters keep_prob = 1 learning_rate = 0.00005 batch_num = 64 max_len = None filter_size = 3 num_heads = 8 #for transformer hidden_dim = 300 #a dim reduction after highway network char_emb_dim=8 ############################## tprint("start loading dataset") mnli = MultiNli("../data/embedding/glove.txt.gz", "../data/multinli_0.9", max_len = max_len, batch=batch_num, train_epoch=1, dev_epoch=1, char_emb_dim=char_emb_dim, pad2=False #all_printable_char=True, #trainfile="multinli_0.9_train_5000.jsonl", ) model = EntailModel("base", hidden_dim, num_heads, filter_size, mnli, learning_rate = learning_rate) model.build() for i in tqdm(range(1000)): tprint(f"train epoch: {i}") model.run(init=model.dataset.train, train=True, name="train") tprint(f"evaluate on dev_matched") model.run(init=model.dataset.dev_matched, name="matched") tprint(f"evaluate on dev_mismatched") model.run(init=model.dataset.dev_mismatched, name="mismatched") tprint("done!")
87265d008eb6bf12e18705e584b68c4bdadec7d8
[ "Python" ]
6
Python
chengchingwen/Entailment_model
cc3a6389e6adc14c69324f2cd4400d62c0df0b0e
9b4ec392f433a12d16821161a29eea5c24cefcdc
refs/heads/main
<repo_name>queer/notify<file_sep>/Cargo.toml [package] name = "notify" version = "5.0.0-pre.10" description = "Cross-platform filesystem notification library" documentation = "https://docs.rs/notify" homepage = "https://github.com/notify-rs/notify" repository = "https://github.com/notify-rs/notify.git" readme = "README.md" license = "CC0-1.0 OR Artistic-2.0" keywords = ["events", "filesystem", "notify", "watch"] categories = ["filesystem"] authors = [ "<NAME> <<EMAIL>>", "<NAME> <<EMAIL>>" ] edition = "2018" exclude = [ "/clippy.toml", ".github/*" ] [dependencies] bitflags = "1.0.4" crossbeam-channel = "0.5.0" filetime = "0.2.6" libc = "0.2.4" serde = { version = "1.0.89", features = ["derive"], optional = true } walkdir = "2.0.1" [target.'cfg(target_os="linux")'.dependencies] inotify = { version = "0.9", default-features = false } mio = { version = "0.7.7", features = ["os-ext"] } [target.'cfg(target_os="macos")'.dependencies] fsevent-sys = "4" [target.'cfg(windows)'.dependencies] winapi = { version = "0.3.8", features = ["fileapi", "handleapi", "ioapiset", "minwinbase", "synchapi", "winbase", "winnt"] } [dev-dependencies] futures = "0.3" serde_json = "1.0.39" tempfile = "3.2.0" [features] timing_tests = [] manual_tests = [] [patch.crates-io] notify = { path = "." } [workspace] members = [ ".", "examples/hot_reload_tide" ] <file_sep>/examples/hot_reload_tide/src/messages.rs use serde::{Deserialize, Serialize}; use std::collections::HashMap; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Config { pub audio_folder_path: String, pub messages: Messages, } /// The key is the audio file name type Messages = HashMap<String, Message>; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Message { pub display_name: String, pub volume: f32, } pub fn load_config(path: &str) -> Result<Config, Box<dyn std::error::Error>> { let file = std::fs::File::open(path)?; let file_size = file.metadata()?.len(); if file_size == 0 { return Err("The config file is empty.".into()); } let reader = std::io::BufReader::new(file); let config: Config = serde_json::from_reader(reader)?; Ok(config) } <file_sep>/src/null.rs //! Stub Watcher implementation #![allow(unused_variables)] use super::{RecursiveMode, Result, Watcher}; use std::path::Path; /// Stub `Watcher` implementation /// /// Events are never delivered from this watcher. pub struct NullWatcher; impl Watcher for NullWatcher { fn watch(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()> { Ok(()) } fn unwatch(&mut self, path: &Path) -> Result<()> { Ok(()) } } <file_sep>/examples/hot_reload_tide/src/main.rs // Imagine this is a web app that remembers information about audio messages. // It has a config.json file that acts as a database, // you can edit the configuration and the app will pick up changes without the need to restart it. // This concept is known as hot-reloading. use hot_reload_tide::messages::{load_config, Config}; use notify::{ event::ModifyKind, Error, Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher, }; use std::path::Path; use std::sync::{Arc, Mutex}; use tide::{Body, Response}; const CONFIG_PATH: &str = "config.json"; // Because we're running a web server we need a runtime, // for more information on async runtimes, please check out [async-std](https://github.com/async-rs/async-std) #[async_std::main] async fn main() -> tide::Result<()> { let config = load_config(CONFIG_PATH).unwrap(); // We wrap the data a mutex under an atomic reference counted pointer // to guarantee that the config won't be read and written to at the same time. // To learn about how that works, // please check out the [Fearless Concurrency](https://doc.rust-lang.org/book/ch16-00-concurrency.html) chapter of the Rust book. let config = Arc::new(Mutex::new(config)); let cloned_config = Arc::clone(&config); // We listen to file changes by giving Notify // a function that will get called when events happen let mut watcher = // To make sure that the config lives as long as the function // we need to move the ownership of the config inside the function // To learn more about move please read [Using move Closures with Threads](https://doc.rust-lang.org/book/ch16-01-threads.html?highlight=move#using-move-closures-with-threads) RecommendedWatcher::new(move |result: Result<Event, Error>| { let event = result.unwrap(); if event.kind == EventKind::Modify(ModifyKind::Any) { match load_config(CONFIG_PATH) { Ok(new_config) => *cloned_config.lock().unwrap() = new_config, Err(error) => println!("Error reloading config: {:?}", error), } } })?; watcher.watch(Path::new(CONFIG_PATH), RecursiveMode::Recursive)?; // We set up a web server using [Tide](https://github.com/http-rs/tide) let mut app = tide::with_state(config); app.at("/messages").get(get_messages); app.at("/message/:name").get(get_message); app.listen("127.0.0.1:8080").await?; Ok(()) } type Request = tide::Request<Arc<Mutex<Config>>>; async fn get_messages(req: Request) -> tide::Result { let mut res = Response::new(200); let config = &req.state().lock().unwrap(); let body = Body::from_json(&config.messages)?; res.set_body(body); Ok(res) } async fn get_message(req: Request) -> tide::Result { let mut res = Response::new(200); let name: String = req.param("name")?.parse()?; let config = &req.state().lock().unwrap(); let value = config.messages.get(&name); let body = Body::from_json(&value)?; res.set_body(body); Ok(res) } <file_sep>/release_checklist.md - update changelog - update readme - update lib.rs - update cargo.toml - bump version number on the root Cargo.toml and examples <file_sep>/.github/ISSUE_TEMPLATE.md <!-- If reporting a bug, fill out the below. Otherwise, if asking a question or suggesting a feature or something else, remove everything before continuing. --> #### System details <!-- Please include ALL of the following: --> - OS/Platform name and version: - Rust version (if building from source): `rustc --version`: - Notify version (or commit hash if building from git): <!-- And as much of the following as you can / think is relevant: --> - If you're coming from a project that makes use of Notify, what it is, and a link to the downstream issue if there is one: - Filesystem type and options: - On Linux: Kernel version: - On Windows: version and if you're running under Windows, Cygwin (unsupported), Linux Subsystem: - If you're running as a privileged user (root, System): - If you're running in a container, details on the runtime and overlay: - If you're running in a VM, details on the hypervisor: <!-- (remove the ones that are not relevant) --> #### What you did (as detailed as you can) #### What you expected #### What happened <!-- Thank you! --> <file_sep>/examples/hot_reload_tide/tests/messages_test.rs use announcer::messages::*; #[test] fn load_config_from_file() { let Config { audio_folder_path, messages, } = load_config("tests/messages_test_config.json").unwrap(); assert_eq!(audio_folder_path, "sounds/"); let message = messages.get("sound.mp3").unwrap(); assert_eq!(message.display_name, "Sound 1"); } <file_sep>/.github/PULL_REQUEST_TEMPLATE.md <!-- By contributing, you agree to the terms of the license, available in the LICENSE.ARTISTIC file, and of the code of conduct, available in the CODE_OF_CONDUCT.md file. Furthermore, you agree to release under CC0, also available in the LICENSE file, until Notify has fully transitioned to Artistic 2.0. --> <!-- After creating this pull request, the test suite will run. It is expected that if any failures occur in the builds, you either: - fix the errors, - ask for help, or - note that the failures are expected with a detailed explanation. If you do not, a maintainer may prompt you and/or do it themselves, but do note that it will take longer for your contribution to be reviewed if the build does not pass. Running `cargo fmt` and/or `cargo clippy` is NOT required but appreciated! You can remove this text. --> <file_sep>/README.md # Notify [![» Crate](https://flat.badgen.net/crates/v/notify)][crate] [![» Docs](https://flat.badgen.net/badge/api/docs.rs/df3600)][docs] [![» CI](https://flat.badgen.net/github/checks/notify-rs/notify/main)][build] [![» Downloads](https://flat.badgen.net/crates/d/notify)][crate] [![» Conduct](https://flat.badgen.net/badge/contributor/covenant/5e0d73)][coc] [![» Public Domain](https://flat.badgen.net/badge/license/CC0-1.0/purple)][cc0] _Cross-platform filesystem notification library for Rust._ **Caution! This is unstable code!** You likely want either [the latest 4.0 release] or [5.0.0-pre.10]. [the latest 4.0 release]: https://github.com/notify-rs/notify/tree/v4.0.16#notify [5.0.0-pre.10]: https://github.com/notify-rs/notify/tree/v5.0.0-pre.10#notify (Looking for desktop notifications instead? Have a look at [notify-rust] or [alert-after]!) - **incomplete [Guides and in-depth docs][wiki]** - [API Documentation][docs] - [Crate page][crate] - [Changelog][changelog] - Earliest supported Rust version: **1.47.0** As used by: [alacritty], [cargo watch], [cobalt], [docket], [mdBook], [pax] [rdiff], [rust-analyzer], [timetrack], [watchexec], [xi-editor], and others. ## Installation ```toml [dependencies] crossbeam-channel = "0.4.0" notify = "5.0.0-pre.10" ``` ## Usage The examples below are aspirational only, to preview what the final release may have looked like. They may not work. Refer to [the API documentation][docs] instead. ```rust use notify::{RecommendedWatcher, RecursiveMode, Result, watcher}; use std::time::Duration; fn main() -> Result<()> { // Automatically select the best implementation for your platform. // You can also access each implementation directly e.g. INotifyWatcher. let mut watcher = watcher(Duration::from_secs(2))?; // Add a path to be watched. All files and directories at that path and // below will be monitored for changes. watcher.watch("/home/test/notify", RecursiveMode::Recursive)?; // This is a simple loop, but you may want to use more complex logic here, // for example to handle I/O. for event in &watcher { match event { Ok(event) => println!("changed: {:?}", event.path), Err(err) => println!("watch error: {:?}", err), }; } Ok(()) } ``` ### With a channel To get a channel for advanced or flexible cases, use: ```rust let rx = watcher.channel(); loop { match rx.recv() { // ... } } ``` To pass in a channel manually: ```rust let (tx, rx) = crossbeam_channel::unbounded(); let mut watcher: RecommendedWatcher = Watcher::with_channel(tx, Duration::from_secs(2))?; for event in rx.iter() { // ... } ``` ### With precise events By default, Notify issues generic events that carry little additional information beyond what path was affected. On some platforms, more is available; stay aware though that how exactly that manifests varies. To enable precise events, use: ```rust use notify::Config; watcher.configure(Config::PreciseEvents(true)); ``` ### With notice events Sometimes you want to respond to some events straight away, but not give up the advantages of debouncing. Notice events appear once immediately when the occur during a debouncing period, and then a second time as usual at the end of the debouncing period: ```rust use notify::Config; watcher.configure(Config::NoticeEvents(true)); ``` ### With ongoing events Sometimes frequent writes may be missed or not noticed often enough. Ongoing write events can be enabled to emit more events even while debouncing: ```rust use notify::Config; watcher.configure(Config::OngoingEvents(Some(Duration::from_millis(500)))); ``` ### Without debouncing To receive events as they are emitted, without debouncing at all: ```rust let mut watcher = immediate_watcher()?; ``` With a channel: ```rust let (tx, rx) = unbounded(); let mut watcher: RecommendedWatcher = Watcher::immediate_with_channel(tx)?; ``` ### Serde Events can be serialisable via [serde]. To enable the feature: ```toml notify = { version = "5.0.0-pre.10", features = ["serde"] } ``` ## Platforms - Linux / Android: inotify - macOS: FSEvents - Windows: ReadDirectoryChangesW - All platforms: polling ### FSEvents Due to the inner security model of FSEvents (see [FileSystemEventSecurity]), some event cannot be observed easily when trying to follow files that do not belong to you. In this case, reverting to the pollwatcher can fix the issue, with a slight performance cost. ## License Notify was undergoing a transition to using the [Artistic License 2.0][artistic] from [CC Zero 1.0][cc0]. A part of the code is only under CC0, and another part, including _all new code_ since commit [`3378ac5a`], is under _both_ CC0 and Artistic. When the project was to be entirely free of CC0 code, the license would be formally changed (and that would have incurred a major version bump). As part of this, contributions to Notify since would agree to release under both. [`3378ac5a`]: https://github.com/notify-rs/notify/commit/3378ac5ad5f174dfeacce6edadd7ded1a08d384e ## Origins Inspired by Go's [fsnotify] and Node.js's [Chokidar], born out of need for [cargo watch], and general frustration at the non-existence of C/Rust cross-platform notify libraries. Written by [<NAME>] and awesome [contributors]. [Chokidar]: https://github.com/paulmillr/chokidar [FileSystemEventSecurity]: https://developer.apple.com/library/mac/documentation/Darwin/Conceptual/FSEvents_ProgGuide/FileSystemEventSecurity/FileSystemEventSecurity.html [<NAME>lli]: https://passcod.name [alacritty]: https://github.com/jwilm/alacritty [alert-after]: https://github.com/frewsxcv/alert-after [artistic]: ./LICENSE.ARTISTIC [build]: https://github.com/notify-rs/notify/actions [cargo watch]: https://github.com/passcod/cargo-watch [cc0]: ./LICENSE [changelog]: ./CHANGELOG.md [cobalt]: https://github.com/cobalt-org/cobalt.rs [coc]: http://contributor-covenant.org/version/1/4/ [contributors]: https://github.com/notify-rs/notify/graphs/contributors [crate]: https://crates.io/crates/notify [docket]: https://iwillspeak.github.io/docket/ [docs]: https://docs.rs/notify/5.0.0-pre.10/notify/ [fsnotify]: https://github.com/go-fsnotify/fsnotify [handlebars-iron]: https://github.com/sunng87/handlebars-iron [hotwatch]: https://github.com/francesca64/hotwatch [mdBook]: https://github.com/rust-lang-nursery/mdBook [notify-rust]: https://github.com/hoodie/notify-rust [pax]: https://pax.js.org/ [rdiff]: https://github.com/dyule/rdiff [rust-analyzer]: https://github.com/rust-analyzer/rust-analyzer [serde]: https://serde.rs/ [timetrack]: https://github.com/joshmcguigan/timetrack [watchexec]: https://github.com/mattgreen/watchexec [wiki]: https://github.com/notify-rs/notify/wiki [xi-editor]: https://xi-editor.io/
3513d3b18d1647b22e7116bf5a4cd6399663a212
[ "TOML", "Rust", "Markdown" ]
9
TOML
queer/notify
1fac9caec14b00f3ef23ace38eb1d1d7d7f0e3f3
f31583f980ddfa664a1c42ebf2e55f740ab7879f
refs/heads/master
<repo_name>lipsworld/meuppt-estilo-shortcodes<file_sep>/README.md # meuppt-estilo-shortcodes Habilita uso de shortcodes de estilo e diversos elementos na edição de posts e páginas <file_sep>/meuppt-estilo.php <?php /* Plugin Name: MeuPPT - Shortcodes, estilos e elementos Plugin URI: https://github.com/lipsworld/meuppt-estilo-shortcodes Description: Habilita uma série de estilos e shortcodes para uso em posts e páginas, mas também classes CSS para edição e modificação de templates. Version: 1.0.0 License: GNU General Public License v2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html Author: MeuPPT Author URI: http://www.meuppt.pt/ Text Domain: security-functions-meuppt ************************************************************************** Copyright (C) 2017 MeuPPT This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. **************************************************************************/ // Aciona e regista folhas de estilo para o admin function meuppt_custom_wp_admin_style() { wp_enqueue_style( 'custom_wp_admin_css', plugins_url('admin-style.css', __FILE__) ); } add_action( 'admin_enqueue_scripts', 'meuppt_custom_wp_admin_style' );
6cf21c6079527ec3db46a672e7dddf1b0c83ad63
[ "Markdown", "PHP" ]
2
Markdown
lipsworld/meuppt-estilo-shortcodes
07db82f27810710073d2938b3a023bb52cb38514
5a90a0bbd03996b8f2ba45d226c1fb005ee18163
refs/heads/master
<repo_name>brenosoares/teste-arquivei<file_sep>/README.md # Teste Arquivei Este projeto tem como base o [Create Reac App](https://github.com/facebook/create-react-app) para rodar basta clonar a basta, entrar na pasta clonada e rodar `npm install` e depois `npm start` ou `yarn start` O projeto irá rodar no link [http://localhost:3000]( http://localhost:3000 ) <file_sep>/src/container/Home/index.js import React, { Component } from 'react' import axios from 'axios' import moment from 'moment' import { Icon } from 'react-icons-kit' import {download} from 'react-icons-kit/fa/download' import {eye} from 'react-icons-kit/fa/eye' // Style import './style.sass' //Components import TopBar from '../../components/TopBar'; import ModalExperimente from '../../components/ModalExperimente'; import ModalNuvem from '../../components/ModalNuvem'; export default class HomeContainer extends Component { constructor(){ super(); this.state = { currentCompany: null, dataNotas: null, listaNotas: null, authorized: false, modalExperiemente: false, modalNuvem: false } } componentDidMount(){ axios.get('http://5b50cee2fe45ed0014cf08e6.mockapi.io/initialState') .then((response) => { const data = response.data data.map((item) => ( this.setState({ currentCompany: item.networkGrowth.currentCompany, dataNotas: item.networkGrowth.data }) )) this.listNotas(this.state.dataNotas) }) .catch((error) => { // handle error console.log(error); }) } listNotas = (data) => { const arr= [] data.map((item, index) => { let diaDoMes = moment(item.emissionDate, "YYYY-MM-DD").format("DD-MM-YYYY") let valorNota = this.formatarValor(item.value) let macaraCNPJ = item.emitter.CNPJ.replace(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/, "$1.$2.$3/$4-$5") return(arr.push( <div className="row" key={index}> <div className="column status"> { item.status === 'authorized' ? this.setState({authorized: true}) : this.setState({authorized: false}) } <div className={ this.state.authorized ? "autorizado" : "desautorizado"}>{ this.state.authorized ? 'Autorizada' : 'Não Autorizada'}</div> </div> <div className="column numero">{item.number}</div> <div className="column emissao">{diaDoMes}</div> <div className="column fornecedor">{item.emitter.XNome}</div> <div className="column valor">{valorNota}</div> <div className="column cnpj">{macaraCNPJ}</div> <div className="column acao"> <div className="btns"> <a className="btn" href="#"><div className="icon"><Icon icon={eye} /></div>Ver Nota</a> <a className="btn" href="#"><div className="icon"><Icon icon={download} /></div>Baixar Xml</a> </div> </div> </div>) ) }) this.setState({listaNotas : arr}) } formatarValor = (amount, decimalCount = 2, decimal = ",", thousands = ".")=> { decimalCount = Math.abs(decimalCount); decimalCount = isNaN(decimalCount) ? 2 : decimalCount; let i = parseInt(amount = Math.abs(Number(amount) || 0).toFixed(decimalCount)).toString(); let j = (i.length > 3) ? i.length % 3 : 0; return 'R$' + (j ? i.substr(0, j) + thousands : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands) + (decimalCount ? decimal + Math.abs(amount - i).toFixed(decimalCount).slice(2) : ""); }; openModalExperimente = () =>{ this.setState({modalExperiemente: true}) } closeModalExperimente = () =>{ this.setState({modalExperiemente: false}) } openModalNuvem = () =>{ this.setState({modalNuvem: true}) } render() { return ( <div> <TopBar /> <div className="topo-notas"> <p>Seu CNPJ / Razão Social:</p> <p className="numero-cnpj">{ this.state.currentCompany ? `[${this.state.currentCompany.state}] [${this.state.currentCompany.cnpj}] ${this.state.currentCompany.name}` : null}</p> </div> <div className="lista-de-notas"> <div className="lista-de-notas-titulo">Existem novas notas contra seu CNPJ</div> <div className="lista-de-notas-tabela"> <div className="row row-head"> <div className="column status">Status</div> <div className="column numero">Número</div> <div className="column emissao">Emissão</div> <div className="column fornecedor">Fornecedor</div> <div className="column valor">Valor</div> <div className="column cnpj">CNPJ</div> <div className="column acao">Ação</div> </div> {this.state.listaNotas} </div> </div> <div className="caixa-dialogo"> <p>Você pode ter as notas de <b>todos os seus fornecedores</b>, que ter acesso a elas?</p> <p><b>Experimente grátis o Arquivei</b> e tenha todas suas notas diretamente da Sefaz</p> <div className="btn-experimentar" onClick={() => this.openModalExperimente()}>Experimentar o Arquivei</div> </div> <ModalExperimente open={this.state.modalExperiemente} close={() => this.closeModalExperimente()} experimente={() => this.openModalNuvem()}/> <ModalNuvem open={this.state.modalNuvem}/> </div> ) } } <file_sep>/src/components/ModalNuvem/index.js import React, { Component } from 'react' import { Icon } from 'react-icons-kit' import {times} from 'react-icons-kit/fa/times' //Style import './style.sass' // Images e Assets import factory from '../../assets/factory.gif' export default class ModalNuvem extends Component { componentDidMount(){ if(this.props.open){ setTimeout(() =>{ window.location = "http://app.arquivei.com.br?token=<PASSWORD>" }, 3000) } } render() { return ( <div className={this.props.open ? "modal open" : "modal"}> <div className="modal-cont nuvem"> <img src={factory} /> <p className="nuvem">Descarregando para a nuvem</p> <div className="load-bar"> <div className="track"></div> <div className="anima"></div> </div> </div> </div> ) } }
77201cabd1316e0c9ffc913ba6ed719ff8bf9951
[ "Markdown", "JavaScript" ]
3
Markdown
brenosoares/teste-arquivei
9fe409b3d11c70032acf40077dcca4fb44c346a8
a09609bf22b384a66fd9169666d87b6b86735bf2
refs/heads/master
<repo_name>iloveicedgreentea/crypto-eink<file_sep>/README.md # crypto-eink This is a display "driver" for my pi0. Very WIP, currently rewriting in Go. Posted here just for reference, this is deprecated and will be replaced soon. This was intended to be used as a passive display to check crypto but the rewrite will make it faster and also make use of the buttons for multiple functions # Usage Copy all files to `/home/pi/driver/` on your pi Rum `run.sh` or set it to run on boot<file_sep>/main.py #! /usr/bin/env python3 from papirus import PapirusComposite import requests from signal import pause from gpiozero import Button from time import sleep class Display: def __init__(self, file_path, coin_limit): """ :param file_path: path to list of coins to check, not greater than coin_limit """ self.url = 'https://coincap.io' self.coin_file_path = file_path self.coin_limit = coin_limit self.driver = PapirusComposite(False, rotation=0) # if false, will wait until writeall is called self.uparrow_path = '' self.downarrow_path = '' self.fontsize = 13 self.debug = True self.coinprice_list = [] self.sw1 = Button(21, pull_up=False) self.sw2 = Button(16, pull_up=True) self.sw3 = Button(20, pull_up=True) self.sw4 = Button(19, pull_up=True) self.sw5 = Button(26, pull_up=True) def draw_image(self, image_path, posX, posY, width, height, picture_id): """ draws an image """ self.driver.AddImg(image=str(image_path), x=posX, y=posY, size=(width, height), Id=str(picture_id)) def update_image(self, image_path, picture_id): """ updates an image """ self.driver.UpdateImg(image=str(image_path), Id=str(picture_id)) def remove_image(self, picture_id): """ removes an image """ self.driver.RemoveImg(Id=str(picture_id)) def draw_text(self, text, posX, posY, fontsize, text_id, fontpath=None): """ draws text """ self.driver.AddText(text=str(text), x=posX, y=posY, size=fontsize, Id=str(text_id)) def update_text(self, text, text_id, fontpath=None): """ updates text """ self.driver.AddText(newText=str(text), Id=str(text_id)) def remove_text(self, text_id): """ removes text """ self.driver.RemoveText(Id=str(text_id)) def write_screen(self): """ writes data to screen """ self.driver.WriteAll() def call_api(self, endpoint, coin_name): # todo: move this to an async external module, write data to a file, fiunction below grabs this file """ Calls the api :param endpoint: the api call i.e history, 1day :param coin_name: ticket name of coin i.e ETH :return: json """ try: request = "{url}/{endpoint}/{coin_name}".format( url=self.url, endpoint=endpoint, coin_name=coin_name.upper() ) # wish debian kept up with the times so I can use f strings response = requests.get(request) if self.debug: print(request) return response.json() except Exception as e: print(e) def get_currentprice(self, coin): """ Gets the price for a single coin :param coin: string e.g ETH :return: price in USD and ETH: tuple(float, float) """ response = self.call_api(endpoint="page", coin_name=coin) price_usd = "${}".format(response.get("price_usd")) price_eth = "e{}".format(response.get("price_eth")) # lazy handling if coin doesn't have eth price, just return USD if response.get("price_eth") is None: price_eth = price_usd return price_usd, price_eth def print_this(self, switch): print(switch) self.draw_text(text=switch, posX=0, posY=0, fontsize=self.fontsize, text_id=switch) self.write_screen() def main(self): """ The bread and butter """ print('started') # need to use reverse logic because the hat buttons are set high while True: if not self.sw1.is_active: print('true') break # from file list, get coins with open(self.coin_file_path, 'r') as file: file_contents = file.readlines() # cant display more than 14 coins if len(file_contents) > 14: raise Exception("Too many coins to list {} > 14".format(len(file_contents))) # for each coin in list, write text to a new line # create an 8x2 grid posx = 0 posy = 0 coin_count = 0 next_grid = 0 for line in file_contents: # split the line into two elements coin = ''.join(line).split(',') try: if self.debug: print("Coin: {}, Format: {}".format(coin[0], coin[1])) print("X: {}, Y: {}".format(posx, posy)) print("count: {}, grid: {} \n\n".format(coin_count, next_grid)) # get the prices price_usd, price_eth = self.get_currentprice(coin[0]) # once the counter gets to 6, draw the next grid, shift 100 px right, reset Y if coin_count > 6 and next_grid is 0: posx = 100 posy = 0 coin_count = 0 next_grid = 1 # check if the coin should be displyed in eth or usd # use one conditional for a marginal speed up texttoprint = "{coin} {price}".format(coin=coin[0].upper(), price=str(price_eth)[:7]) if 'usd' in coin[1]: texttoprint = "{coin} {price}".format(coin=coin[0].upper(), price=str(price_usd)[:7]) # draw the text self.draw_text(text=texttoprint, posX=posx, posY=posy, fontsize=self.fontsize, text_id=coin[0]) # increment counters posy += 13 coin_count += 1 except IndexError: pass # cheap way to stop index out of range if there are blank lines # get the last candle or something last_candle = '' # write up or down to file with open('candles.txt', 'a') as candle_file: candle_file.writelines("{}".format(last_candle)) # or compare the number to the previous, then you know if up or down self.write_screen() if __name__ == "__main__": coin_file_path = "coinlist.txt" display = Display(file_path=coin_file_path, coin_limit=14) display.main() <file_sep>/run.sh # refresh every 30 seconds while true; do python3 /home/pi/driver/main.py sleep 30 done
64c163762b33865e5a5dd6be766fac91b7df4055
[ "Markdown", "Python", "Shell" ]
3
Markdown
iloveicedgreentea/crypto-eink
b9f0b454ea11017d426e6abe6cb594eb51bf00f2
0dc218a9ebceb677184a504066bcdc36a3b8d5dc
refs/heads/master
<file_sep># my-o-FirstAirGuitar ## Initialization ### Requirements * Myo Connect and SDK ([Windows / Mac](https://developer.thalmic.com/downloads)) - you will have to sign up for a Myo Developer Account (just takes email) * Python 2.7.9 (pre-installed on Macs, on Windows go [here](https://www.python.org/downloads/release/python-279/)) * Git Unfortunately, Myo Connect and the Myo SDK don't come packaged for Linux distros at this time, so you're stuck with either Mac or Windows. ### Setup Procedure #### Myo *** Download Myo Connect and the Myo SDK (from Requirements) Set up your Myo typically - you can follow the linked instructions ([Windows](https://support.getmyo.com/hc/en-us/articles/202657596-Getting-starting-with-Myo-on-Windows) / [Mac](https://support.getmyo.com/hc/en-us/articles/202667496-Getting-starting-with-Myo-on-Mac-OS-X)), but in most cases, it's as easy as running Myo Connect and following the prompts. Make sure you're putting the Myo on with the connector port facing your wrist and the Myo symbol plate on top of your forearm (last part is not required by Myo, but helpful for us if we want to have similar channels showing similar data). You should be able to perform all 5 officially supoorted gestures and have them recognized by Myo Connect - it's not super relevant to the project, but it ensures that you have the Myo on properly and that EMG connectivity works. You might want to set up a custom calibration profile. Add the path of the framework file from the Myo SDK (e.g. "/Users/[user_name]/Downloads/sdk/myo.framework") to the required system variable (PATH on Windows, DYLD_LIBRARY_PATH - full instructions [here](http://developerblog.myo.com/myo-unleashed-python/)). #### Git *** If you don't have [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) or [GitHub Desktop](https://desktop.github.com/) installed, install either one now. [Clone](https://help.github.com/articles/cloning-a-repository/) this repository to somewhere where you won't randomly delete it. #### FirstAirGuitar *** Open up a terminal window, navigate to the directory that you've cloned this repository into, and enter ```pip install -r requirements.txt``` (you can also do this in a virtual environment, if you have that [set up](http://docs.python-guide.org/en/latest/dev/virtualenvs/), but otherwise you don't need to bother). The install may take a while because of scipy's ridiculously long list of compiled dependencies. You should now be able to run anything in the repository, but let me know if you can't. This documentation is still a work in progress. ## Use Right now, my work-flow is as follows: 1. I run a listener script to gather data, following the prompts as they show up in the terminal window: ```python gesture_classifier_5.py``` The data gets stored to a pkl file in a directory called "data" in the same folder. 2. I pre-process the data, as the arrays of EMG channel data aren't properly shaped when stored. ```python preprocessing.py [hyphenated-date-time]_myo_data.pkl``` 3. I import the gesture classifier neural network model I've made for the scenario, and check the accuracy of classification on the data that I've recorded and preprocessed. ```python gesture_classifier_5.py data/[hyphenated-date-time]_myo_data.pkl.proc``` Obviously, this isn't optimal, but I've mostly just been using Jupyter Notebook to visualize the data and check accuracy. I can also start tracking my Notebook file if you think that would be of use to you. Otherwise, improvements that I think could be done are currently being tracked in issues.<file_sep>import myo as libmyo import copy from myo_listener_freestyle import EmgListen, lblDataDump def main(): fing_curv = [] trial_data = [] libmyo.init() listener = EmgListen() hub = libmyo.Hub() try: # warm up (first run seems to have shorter data length, idk why) hub.run_once(1000, listener) listener.store_data = [] # clear stored data between runs if len(listener.store_data) == 0: # make sure it's cleared print "Run, cleared, and flushed!" else: raise RuntimeError("store_data cache not flushed!") print("""Bend your fingers as indicated by the printed array\n where 1 indicates bent and 0 indicates unbent,\n starting with your thumb and ending with your pinky.\n E.g. index finger bent, the rest unbent would be '01000':\n""") # 2^5 possible configurations for five fingers, on/off for n in range(2**5): while True: print(list('{0:05b}'.format(n))) raw_input("Form the indicated hand shape. Press Enter when ready.") hub.run_once(3000, listener) confirm = raw_input("Enter to save or any other input to deny.") if confirm == '': print("Saved.") trial_data.append(copy.deepcopy(listener.store_data)) fing_curv.append([[int(x) for x in list('{0:05b}'.format(n))] for datum in listener.store_data]) listener.store_data = [] # clear stored data between runs if len(listener.store_data) == 0: # make sure it's cleared print "Run, cleared, and flushed!" else: raise RuntimeError("store_data (len {0}) not flushed!" .format(len(listener.store_data))) break else: print("Data was not saved.") finally: hub.stop(True) hub.shutdown() lblDataDump(trial_data, fing_curv) if __name__ == '__main__': main() <file_sep>from keras.models import Sequential from keras.layers import Dense, Dropout, Activation from keras.optimizers import SGD import pickle import argparse import os import numpy as np class nur_net(object): model = None def __init__(self, h_lay=2, num_outputs=5): model = Sequential() # Dense(32) is a fully-connected layer with 64 hidden units. # in the first layer, you must specify the expected input data shape: # here, 20-dimensional vectors. model.add(Dense(32, input_dim=8, init='uniform')) model.add(Activation('tanh')) model.add(Dropout(0.5)) for i in range(h_lay-1): model.add(Dense(32, init='uniform')) model.add(Activation('tanh')) model.add(Dropout(0.5)) model.add(Dense(num_outputs, init='uniform')) model.add(Activation('softmax')) sgd = SGD(lr=0.001, decay=1e-6, momentum=0.9, nesterov=True) model.compile(loss='categorical_crossentropy', optimizer=sgd) self.model = model def train(self, x, y, eps=30, batch_sz=None): if batch_sz is None: batch_sz = len(x)/100 self.model.fit(x, y, nb_epoch=eps, batch_size=batch_sz, show_accuracy=True) def loss(self, x, y): return self.model.evaluate(x, y, batch_size=1000) def accuracy(self, x, y): return self.model.test_on_batch(x, y, accuracy=True) def predict(self, x, batch_sz=128): return self.model.predict(x, batch_size=batch_sz, verbose=0) def save(self, fname): return self.model.save_weights(fname, overwrite=False) def load(self, fname): return self.model.load_weights(fname) def main(): parser = argparse.ArgumentParser(description='Try machine learning on Myo data file') parser.add_argument('filepath', type=str, default='', help='filepath of .pkl file to be analyzed') parser.add_argument('-hl', '--hidden', type=int, default=2, help='number of hidden layers to use in the model') parser.add_argument('-e', '--epochs', type=int, default=30, help='number of training epochs to run') args = parser.parse_args() if not args.filepath: try: f = [] for (dirpath, dirnames, filenames) in os.walk(os.getcwd()): f.extend(filenames) break for file in f: if ".pkl" in file: args.filepath = file break except: raise RuntimeError('No file in current directory available for analysis.') samples = pickle.load(open(args.filepath, 'r')) myo_net = nur_net(args.hidden) x_data = np.array(samples['data']).T y_data = np.array(samples['labels']).T myo_net.train(x_data, y_data, eps=args.epochs) [loss, acc] = myo_net.accuracy(x_data, y_data) acc = int(acc*100) save_name = "{0}_lw_h{1}_e{2}_a{3}".format(args.filepath.split('.')[0], args.hidden, args.epochs, acc) myo_net.save(save_name) if __name__ == "__main__": main() <file_sep>#!/usr/bin/env python import os import signal import subprocess from getch import getch from time import sleep # You need to install SoX - Sound eXchange # homebrew install: # http://brewformulas.org/Sox # sourceforge: # http://sox.sourceforge.net/ # Other ways to install: # http://superuser.com/questions/279675/installing-sox-sound-exchange-via-the-terminal-in-mac-os-x # Usage: # http://sox.sourceforge.net/sox.html DEVNULL = open(os.devnull, 'wb') class chord(object): notes = None name = None ringing = [] def __init__(self, name, *args): self.name = name self.notes = args def play(self, duration=3, delay_inc=0.015): delay = 0 for i in self.notes: if i == "X": pass else: self.ringing.append( subprocess.Popen(['play', '-n', 'synth', 'pluck', i, 'delay', str(delay), 'fade', '0', str(duration), '.1', 'norm', '-1'], stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL, preexec_fn=os.setsid)) delay = delay + delay_inc def reverse(self): return chord(self.name, *list(reversed(list(self.notes)))) def stop(self): for string in self.ringing: os.killpg(os.getpgid(string.pid), signal.SIGTERM) self.ringing = [] class Guitar(object): strings = ['E2', 'A2', 'D3', 'G3', 'B3', 'E4'] scale = ["A", "A#", 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#'] ringing = [None for string in strings] capo = 0 over = 0 gain = 0 sustain = 0 DEVNULL = open(os.devnull, 'wb') def __init__(self, tuning=None, overdrive=0, gain=-40, sus=3): if tuning is not None: self.tune(tuning) self.over = overdrive self.gain = gain self.sustain = sus def strum_chord(self, notes, up=False, delay_inc=0.015, power=0): assert isinstance(notes, list) and isinstance(notes[0], str),\ "{0} is not a list of strings.".format(notes) delay = 0 + len(self.strings) * delay_inc * up way = 1 * -up for index in range(len(self.strings)): if notes[index] == "X": if self.ringing[index] is not None: self.mute_string(index) elif notes[index] == "S": # just here for symbolism - sometimes we want to sustain notes # while changing chords, and using S the note spot supports it pass else: if self.ringing[index] is not None: self.mute_string(index) self.ringing[index] = \ subprocess.Popen(['play', '-n', 'synth', 'pluck', notes[index], 'delay', str(delay), 'fade', '0', str(self.sustain), '.1', 'overdrive', str(self.over), 'gain', '-e', str(self.gain+20*power), 'norm', '-1'], stdin=self.DEVNULL, stdout=self.DEVNULL, stderr=self.DEVNULL, preexec_fn=os.setsid) delay = delay + delay_inc # frets should be a list of strings to allow for X's on not played notes def strum_fret(self, frets=None, up=False, delay_inc=0.015, power=0): if frets is not None: assert isinstance(frets, list) and isinstance(frets[0], str),\ "{0} is not a list of strings.".format(frets) # turn that sucker into a list of notes instead, using capo and scale # as the other other inputs - X gets muted, S gets sustained notes = self.fret_to_notes(frets) self.strum_chord(notes, power=power) def tune(tuning): # assert something about tuning char set here too assert isinstance(tuning, list), \ "Tuning is not a list - how am I tuning to {0}?".format(tuning) if isinstance(tuning[0], str): self.strings = tuning elif isinstance(tuning[0], int): pass else: raise ValueError("We don't handle {0} as tuning!".format(tuning)) def set_distortion(self, dist_int): self.over = dist_int def silence(self): for index in range(len(self.ringing)): self.mute_string(index) def mute_string(self, index): try: os.killpg(os.getpgid(self.ringing[index].pid), signal.SIGTERM) self.ringing[index] = None except: pass def inc_to_note(self, old_note, inc): # split string tuning into note and number # go up scale to current position for note name, # resetting to A after G# and inc number if nes noteName = old_note[:-1] noteNum = int(old_note[-1]) note = "{0}{1}".format( self.scale[(self.scale.index(noteName) + inc) % len(self.scale)], noteNum + inc / len(self.scale) ) return note def fret_to_notes(self, frets): notes = [] for ind in range(len(frets)): f = frets[ind] if f == "X" or f == "S": notes.append(f) else: try: inc = int(f) if f != '0' else self.capo except: raise ValueError("{0} is not a fret character!".format(f)) else: notes.append(self.inc_to_note(self.strings[ind],inc)) return notes # We can also define sharps and flats: # G# or Gb # All notes are relative to middle A (440 hz) g_chord = chord('G', 'G2', 'B3', 'D3', 'G3', 'B3', 'G4') d_chord = chord('D', 'D3', 'A3', 'D4', 'F#4') em_chord = chord('Em', 'E2', 'B2', 'E3', 'G3', 'B3', 'E4') c_chord = chord('C', 'C3', 'E3', 'G3', 'C4', 'E4') chord_dict = {'A': g_chord, 'S': d_chord, 'D': em_chord, 'F': c_chord, 'Z': g_chord.reverse(), 'X': d_chord.reverse(), 'C': em_chord.reverse(), 'V': c_chord.reverse()} if __name__ == "__main__": s = None note = str(getch()).upper() while True: print note, if note in chord_dict: if s: try: s.stop() except: pass s = chord_dict[note] s.play() elif note == 'M': if s: try: s.stop() except: pass elif note == 'Q': break note = str(getch()).upper() <file_sep>Cython==0.23.4 h5py==2.5.0 Keras==0.3.2 myo-python==0.2.2 numpy==1.10.4 PyYAML==3.11 scipy==0.17.0 six==1.10.0 Theano==0.8.0.dev0 <file_sep># gesture_classifier_chords from gesture_classifier_5 import nur_net from keras.utils import np_utils import pickle import argparse import os import numpy as np # fix for python 2->3 try: input = raw_input except NameError: pass def rect_ave(np_arr, window_size=None): if len(np_arr.shape) > 1: raise RuntimeError("Shape {0} is not accepted, feed me a 1xN array") else: x = np.absolute(np_arr) if window_size is None: window = len(x)/20 if len(x)/20 > 5 else 5 else: window = window_size return np.convolve(x, np.ones((window,))/window, 'same') class Category(object): uniques = [] def __init__(self, string_array): if isinstance(string_array[0], list): string_array = self.iterFlatten(string_array) self.uniques = list(set(string_array)) def __getitem__(self, index): if isinstance(index, str): if index in self.uniques: return self.uniques.index(index) else: raise IndexError("{0} is not categorized here ({1}).".format(index, self.uniques)) elif isinstance(index, int): if index < len(self.uniques): return self.uniques[index] else: raise IndexError("{0} is longer than the the length({1}) of this array.".format(index, len(self.uniques))) else: raise IndexError("{0} is neither a String nor an Int. Please check your data inputs") def to_categorical(self, np_array): # currently stored as strings int_array = [self[string] for string in np_array] return np_utils.to_categorical(int_array) def from_categorical(self, np_array): guess = np.argmax(np_array) return self[guess] def iterFlatten(self, root, level=None): if level and level == 0: yield root elif isinstance(root, (list, tuple)): if level: level = level-1 for element in root: for e in self.iterFlatten(element, level): yield e else: yield root def main(): # standard - argparser for arguments and load pickle file parser = argparse.ArgumentParser(description='Try machine learning on Myo data file') parser.add_argument('filepath', type=str, default='', help='filepath of .pkl file to be analyzed') parser.add_argument('-hl', '--hidden', type=int, default=2, help='number of hidden layers to use in the model') parser.add_argument('-e', '--epochs', type=int, default=30, help='number of training epochs to run') parser.add_argument('-b', '--batch', type=int, default=None, help='size of mini-batches for each epoch') parser.add_argument('-s', '--split', type=float, default=0.25, help='data split-off to be used as test data') parser.add_argument('-w', '--window', type=int, default=30, help='size of moving average window on (100 Hz to 200 Hz expected sampling rate)') # Ryan ran 50 separate trials, so we're configuring this to run for multiple files args = parser.parse_args() fpaths = [] if not args.filepath: try: f = [] for (dirpath, dirnames, filenames) in os.walk(os.getcwd()): f.extend(filenames) break for file in f: if ".pkl" in file: fpaths.append(os.path.join(args.filepath, filenames)) except: raise RuntimeError('No file in current directory available for analysis.') elif os.path.isdir(args.filepath): try: f = [] for (dirpath, dirnames, filenames) in os.walk(args.filepath): f.extend(filenames) break for file in f: if ".pkl" in file: fpaths.append(os.path.join(args.filepath, file)) except: raise RuntimeError('No file in {0} available for analysis.'.format(args.filepath)) elif os.path.isfile(args.filepath): fpaths.append(args.filepath) # build the neural net and train against the first set of data with open(fpaths[0], 'r') as data_file: data = pickle.load(data_file) catter = Category(data["labels"]) myo_net = nur_net(args.hidden, len(catter.uniques)) for tri_ind in range(len(data['data'])): for chan_ind in range(len(data['data'][tri_ind])): data['data'][tri_ind][chan_ind] = rect_ave(np.array(data['data'][tri_ind][chan_ind]), window_size=args.window) x = np.concatenate(data['data'], 1).T y = catter.to_categorical(np.concatenate(data['labels'], 0)) # overall_data to test against through iterations overall_data = x overall_results = y # load all the other data for file in fpaths[1:]: with open(file, 'r') as data_file: data = pickle.load(data_file) for tri_ind in range(len(data['data'])): for chan_ind in range(len(data['data'][tri_ind])): data['data'][tri_ind][chan_ind] = rect_ave(np.array(data['data'][tri_ind][chan_ind]), window_size=args.window) x = np.concatenate(data['data'], 1).T y = catter.to_categorical(np.concatenate(data['labels'], 0)) overall_data = np.concatenate([overall_data, x]) overall_results = np.concatenate([overall_results, y]) print(len(overall_data)) split_index = int(args.split*len(overall_data)) if args.batch: myo_net.train(overall_data[:split_index], overall_results[:split_index], eps=args.epochs, batch_size=args.batch) else: myo_net.train(overall_data[:split_index], overall_results[:split_index], eps=args.epochs) [loss, acc] = myo_net.accuracy(overall_data, overall_results) print("loss = {0}".format(loss)) print("accuracy = {0}".format(acc)) name = input("If you'd like to save this run, please enter a savefile name now: ") if name: # save weights myo_net.save(name) print("saved!") # save configuration # save accuracy and loss if __name__ == "__main__": main() <file_sep>import myo as libmyo import pickle import copy import os from datetime import datetime as dt import numpy as np class EmgListen(libmyo.DeviceListener): store_data = [] def on_arm_sync(self, myo, *args): print("on_arm_sync") myo.set_stream_emg(libmyo.StreamEmg.enabled) def on_emg_data(self, myo, timestamp, emg): self.store_data.append(emg) def lblDataDump(data, labels, fName=None, sName=None): all_trials = [] for trial in data: trial_data = [[] for channels in trial[0]] for channel_no in range(len(np.array(trial).T)): trial_data[channel_no].extend(np.array(trial).T[channel_no]) all_trials.append(trial_data) cwd = os.path.dirname(os.path.realpath(__file__)) sN = os.path.basename(os.path.realpath(__file__)).split('_')[-1] if not os.path.isdir("{0}/{1}".format(cwd, "data")): os.makedirs("{0}/{1}".format(cwd, "data")) dtStr = "{:%y-%m-%d_%H-%M-%S}".format(dt.now()) if sName: sN = sName if fName is None: fName = "{0}/{1}/{2}_{3}{4}.pkl".format(cwd, "data", dtStr, 'myo-', sN) labeled_data = {'data': all_trials, 'labels': labels} with open(fName, 'w') as handle: pickle.dump(labeled_data, handle) def main(): fing_curv = [] trial_data = [] libmyo.init() listener = EmgListen() hub = libmyo.Hub() try: hub.run_once(1000, listener) listener.store_data = [] # clear stored data between runs if len(listener.store_data) == 0: # make sure it's cleared print("Run, cleared, and flushed!") else: raise RuntimeError("store_data cache not flushed!") while True: print("""Enter the current position of your fingers,\n where 0 indicates unbent and x > 0 is some measure of bent,\n Separated by spaces, starting with thumb and ending with pinky.\n E.g. index finger very bent, rest unbent would be '0 3 0 0 0':""") str_fing = raw_input("-->") try: fing = [int(x) for x in str_fing.split(" ")] finally: if len(fing) != 5: raise StopIteration("Done Gathering Data") raw_input("Form the indicated hand shape. Press Enter when ready.") hub.run_once(3000, listener) confirm = raw_input("Enter to save or any other input to deny.") if confirm == '': print("Saved.") trial_data.append(copy(listener.store_data).deepcopy()) fing_curv.append([fing for datum in listener.store_data]) listener.store_data = [] # clear stored data between runs if len(listener.store_data) == 0: # make sure it's cleared print("Run, cleared, and flushed!") else: raise RuntimeError("store_data (len {0}) not flushed!" .format(len(listener.store_data))) else: print("Data was not saved.") except: lblDataDump(trial_data, fing_curv, fName='partial') raise else: lblDataDump(trial_data, fing_curv) finally: hub.stop(True) hub.shutdown() if __name__ == '__main__': main() <file_sep>#!/usr/bin/env python from time import sleep from myo import init, Hub, DeviceListener class Listener(DeviceListener): prev_x = 0 prev_mag = 0 def on_pair(self, myo, timestamp, firmware_version): print("Hello, Myo!") def on_unpair(self, myo, timestamp): print("Goodbye, Myo!") # change from negative x to positive x is a strum def on_accelerometor_data(self, myo, timestamp, acceleration): if self.prev_x < 0 and acceleration.x > 0: print("Strummed") self.prev_x = acceleration.x init() hub = Hub() hub.run(1000, Listener()) try: while hub.running: sleep(0.5) except KeyboardInterrupt: print('\nQuit') finally: hub.shutdown() # !! crucial <file_sep>import myo as libmyo import numpy as np import time import threading import argparse from getch import getch from doubleMyoGuitar import RingBuffer from gesture_classifier_5 import nur_net from gesture_classifier_chords import Category from play_chords import chord, g_chord, d_chord, em_chord, c_chord stdChordDict = {'G': g_chord, 'D': d_chord, 'C': c_chord, 'Em': em_chord} store_data = [RingBuffer(30) for channel in range(8)] time_stamp = RingBuffer(30) class EmgListen(libmyo.DeviceListener): global store_data global time_stamp def on_arm_sync(self, myo, *args): print("on_arm_sync") myo.set_stream_emg(libmyo.StreamEmg.enabled) def on_emg_data(self, myo, timestamp, emg): for channel_no in range(len(emg)): store_data[channel_no].append(emg[channel_no]) time_stamp.append(timestamp) def listen(): libmyo.init() listener = EmgListen() hub = libmyo.Hub() hub.run(1000, listener) try: while hub.running: time.sleep(0.5) except KeyboardInterrupt: print("Quitting...") finally: hub.shutdown() def main(): # standard - argparser for arguments and load pickle file parser = argparse.ArgumentParser(description='Air Guitar on Myo!') parser.add_argument('-f', '--filepath', type=str, default='', help='filepath of weight file to be loaded') parser.add_argument('-hl', '--hidden', type=int, default=3, help='number of hidden layers to use in the model') parser.add_argument('-w', '--window', type=int, default=30, help='size of moving average window on (100 Hz to 200 Hz expected sampling rate)') args = parser.parse_args() if args.filepath: catter = Category(stdChordDict.keys()) loaded = nur_net(args.hidden, len(catter.uniques)) loaded.load(args.filepath) else: raise Exception("Need to load a neural network - using weights from a file!") listener = threading.Thread(target=listen) listener.start() while True: key = str(getch()).upper() if key == ' ': channels = [np.mean(np.abs(datum.get())) for datum in store_data] prediction = loaded.predict(np.array([channels])) print(catter.from_categorical(prediction)) stdChordDict[catter.from_categorical(prediction)].play() elif key == 'Q': break key = str(getch()).upper() if __name__ == "__main__": main() <file_sep># pkl to matlab converter # if run, makes matlab versions of all pkl files in directory import pickle import scipy.io import os cwd = os.path.dirname(os.path.realpath(__file__)) def convert_to_mat(pkl_fname): with open(pkl_fname, 'rb') as data_file: data = pickle.load(data_file) if not os.path.isdir("{0}/{1}".format(cwd, "mat")): os.makedirs("{0}/{1}".format(cwd, "mat")) scipy.io.savemat('./mat/{0}.mat'.format(pkl_fname), mdict={'data': data['data'], 'labels': data['labels']}) def main(): print("converting all .pkl files in {0}".format(os.getcwd())) # temporary storage for unix versions of file - might be from windows if not os.path.isdir("{0}/{1}".format(cwd, "tmp_unix")): os.makedirs("{0}/{1}".format(cwd, "tmp_unix")) for file in os.listdir("."): if file.endswith(".pkl"): text = open(file, 'rb').read().replace('\r\n', '\n') open("tmp_unix/unix_{0}".format(file), 'wb').write(text) convert_to_mat("tmp_unix/unix_{0}".format(file)) if __name__ == "__main__": main()<file_sep>import myo as libmyo import numpy as np import time import argparse from gesture_classifier_5 import nur_net from gesture_classifier_chords import Category from play_chords import chord, g_chord, d_chord, em_chord, c_chord stdChordDict = {'G': g_chord, 'D': d_chord, 'C': c_chord, 'Em': em_chord} # https://scimusing.wordpress.com/2013/10/25/ring-buffers-in-pythonnumpy/ # fast ring buffers for computation class RingBuffer(): "A 1D ring buffer using numpy arrays" def __init__(self, length): self.data = np.zeros(length, dtype='f') self.index = 0 def extend(self, x): "adds array x to ring buffer" x_index = (self.index + np.arange(x.size)) % self.data.size self.data[x_index] = x self.index = (x_index[-1] + 1) % self.data.size def append(self, x): "adds element to ring buffer" self.data[self.index] = x self.index = (self.index + 1) % self.data.size def get(self): "Returns the first-in-first-out data in the ring buffer" idx = (self.index + np.arange(self.data.size)) % self.data.size return self.data[idx] def ringbuff_numpy_test(): ringlen = 100000 ringbuff = RingBuffer(ringlen) rand = np.random.randn(9999) start_time = time.clock() for i in range(40): ringbuff.extend(rand) # write ringbuff.get() # read print(time.clock() - start_time, "seconds") class EmgListen(libmyo.DeviceListener): store_data = None time_stamp = None prev_x = 0 prev_mag = 0 left_myo = None right_myo = None catter = None nnet = None chords = None def __init__(self, model=None, chords=stdChordDict, window=30): libmyo.DeviceListener.__init__(self) self.store_data = [RingBuffer(window) for channel in range(8)] self.time_stamp = RingBuffer(window) self.catter = Category(chords.keys()) self.nnet = model self.chords = chords def on_arm_sync(self, myo, timestamp, arm, x_direction, rotation, warmup_state): print("on_arm_sync") if arm == arm.left: print("left arm connected!") self.left_myo = myo.value myo.set_stream_emg(libmyo.StreamEmg.enabled) elif arm == arm.right: print("right arm connected!") self.right_myo = myo.value def on_emg_data(self, myo, timestamp, emg): if myo.value == self.left_myo: for channel_no in range(len(emg)): self.store_data[channel_no].append(emg[channel_no]) self.time_stamp.append(timestamp) elif myo.value == self.right_myo: raise RuntimeError("Right Myo EMG is turned on - not supposed to happen. Did you cross the streams?") # change from negative x to positive x is a strum def on_accelerometor_data(self, myo, timestamp, acceleration): if myo.value == self.left_myo: pass elif myo.value == self.right_myo: if self.prev_x < 0 and acceleration.x > 0: channels = [np.mean(np.abs(datum.get())) for datum in self.store_data] prediction = self.nnet.predict(np.array([channels])) print(self.catter.from_categorical(prediction)) self.chords[self.catter.from_categorical(prediction)].play() # insert some code for reacting to a strum here elif self.prev_x > 0 and acceleration.x < 0: channels = [np.mean(np.abs(datum.get())) for datum in self.store_data] prediction = self.nnet.predict(np.array([channels])) print(self.catter.from_categorical(prediction)) self.chords[self.catter.from_categorical(prediction)].reverse.play() # insert some code for reacting to a strum here self.prev_x = acceleration.x def main(): parser = argparse.ArgumentParser(description='Air Guitar on Myo!') parser.add_argument('-f', '--filepath', type=str, default='', help='filepath of weight file to be loaded') parser.add_argument('-hl', '--hidden', type=int, default=3, help='number of hidden layers to use in the model') parser.add_argument('-w', '--window', type=int, default=30, help='size of moving average window on (100 Hz to 200 Hz expected sampling rate)') args = parser.parse_args() if args.filepath: catter = Category(stdChordDict.keys()) loaded = nur_net(args.hidden, len(catter.uniques)) loaded.load(args.filepath) else: raise Exception("Model expected - we currently don't build this anywhere else") # myo init and run libmyo.init() hub = libmyo.Hub() dubGuitar = EmgListen(model=loaded, window=args.window) hub.run(1000, dubGuitar) try: while hub.running: time.sleep(0.5) except KeyboardInterrupt: print('\nQuit') finally: hub.shutdown() # !! crucial if __name__ == "__main__": main() <file_sep>import myo as libmyo import copy import re from myo_listener_freestyle import EmgListen, lblDataDump def scrape_chords(tab_file): chords = [] fingerings = {} chord_arr = set(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'm', 's', 'u', '9', '7', '4', '#', '/', '\\', ' ', '\t', '\n']) fing_syn = re.compile("([A-z0-9#/\\\]{1,9})[ \t]*\(?([ 0-9x]{6,18})\)?") with open(tab_file, 'r') as tab: for line in tab.readlines(): # check if this is a line that contains chord names if set(list(line)) <= chord_arr: chordLine = re.findall("\S*", line) for chord in chordLine: # remove blank results if chord != '': chords.append(chord) # TODO: consider scraping chord fingerings from web as well elif fing_syn.match(line): match_obj = fing_syn.match(line) fingerings[match_obj.groups()[0]] = match_obj.groups()[1] return list(set(chords)), fingerings def main(chords=['G', "C", "Em", "D", "No chord - relax your hand"], fingerings={}): fing_curv = [] trial_data = [] libmyo.init() listener = EmgListen() hub = libmyo.Hub() try: # warm up (first run seems to have shorter data length, idk why) hub.run_once(1000, listener) listener.store_data = [] # clear stored data between runs if len(listener.store_data) == 0: # make sure it's cleared print("Run, cleared, and flushed!") else: raise RuntimeError("store_data cache not flushed!") print("""Bend your fingers to form the indicated chord\n as you know the fretting - if you don't know the chord,\n use the first result from Googling the chord name.\n "E.g. Em7 (022033):\n""") # record EMG data per chord for chord in chords: while True: if chord in fingerings: print("{0} ({1})".format(chord, fingerings[chord])) else: print(chord) raw_input("Form the indicated chord. Press Enter when ready.") hub.run_once(3000, listener) confirm = raw_input("Enter to save or any other input to deny.") if confirm == '': print("Saved.") trial_data.append(copy.deepcopy(listener.store_data)) fing_curv.append([chord for datum in listener.store_data]) listener.store_data = [] # clear stored data between runs if len(listener.store_data) != 0: # make sure it's cleared raise RuntimeError("store_data (len {0}) not flushed!" .format(len(listener.store_data))) break else: print("Data was not saved.") finally: hub.stop(True) hub.shutdown() lblDataDump(trial_data, fing_curv) if __name__ == '__main__': #chords, fingerings = scrape_chords('wonderwall_tab.txt') main() <file_sep>import pickle import numpy as np import argparse import os import copy def load_pkl(filepath): with open(filepath, 'r') as data_file: data = pickle.load(data_file) return data def rect_ave(np_arr, window_size=None): if len(np_arr.shape) > 1: raise RuntimeError("Shape {0} is not accepted, feed me a 1xN array") else: x = np.absolute(np_arr) if window_size is None: window = len(x)/20 if len(x)/20 > 5 else 5 else: window = window_size return np.convolve(x, np.ones((window,))/window, 'same') if __name__ == "__main__": parser = argparse.ArgumentParser(description='Rectify and convolve Myo data, storing it in a new object.') parser.add_argument('filepath', type=str, default='', help='filepath of .pkl file to be converted') args = parser.parse_args() if not args.filepath: try: f = [] for (dirpath, dirnames, filenames) in os.walk(os.getcwd()): f.extend(filenames) break for file in f: if ".pkl" in file: args.filepath = file break except: raise RuntimeError('No file in current directory available for conversion.') data = load_pkl(args.filepath) for trial in data['data']: for channel in data: channel = rect_ave(channel) with open('{0}.proc'.format(args.filepath), 'w') as new_data: pickle.dump(data, new_data) <file_sep>#!/usr/bin/env python import subprocess from getch import getch import os from time import sleep # You need to install SoX - Sound eXchange # homebrew install: # http://brewformulas.org/Sox # sourceforge: # http://sox.sourceforge.net/ # Other ways to install: # http://superuser.com/questions/279675/installing-sox-sound-exchange-via-the-terminal-in-mac-os-x # Usage: # http://sox.sourceforge.net/sox.html DEVNULL = open(os.devnull, 'wb') class chord: def __init__(self, *args): self.notes = args def play(self, duration=3): for i in self.notes: subprocess.Popen(['play', '-n', 'synth', str(duration) , 'pluck', i], stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL) # We can also define sharps and flats: # G# or Gb # All notes are relative to middle A (440 hz) notes = ['A', 'B', 'C', 'D', 'E', 'F', 'G'] note = str(getch()).upper() while True: print note, if note in notes: s = chord(note) s.play() elif note == 'Q': break note = str(getch()).upper()
4d58e631e60d57d8dd46559487515323e468c637
[ "Markdown", "Python", "Text" ]
14
Markdown
hexavi42/my-o-FirstAirGuitar
7212f540e86149b1cc96357280dd246dc5ac70b7
676280573225a5c9060215131ce0d0c55e3c671c
refs/heads/master
<file_sep>package launcher; import java.awt.Color; import java.awt.Desktop; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Toolkit; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.awt.Font; import java.awt.FontFormatException; import java.awt.font.FontRenderContext; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; public class Main{ private static final int WIDTH = 900; private static final int HEIGHT = 550; private static final int titleBarHeight = 40; private static final float titleHeight = .75f;//percent of title bar height; private static final int titleButtonSize = 4;//arbitrary value. minimum: 3 private static final float buttonSize = .08f;//percent of content area height private static final float playWidth = 3f;//multiplier of height private static final float textSize = .04f;//percent of content area height private static final float tabTextHeight = .9f;//percent of content area height private static final float headerHeight = .1f;//percent of content area height private static final float buttonIndent = 1.5f;//indent from right side of screen private static final float playIndent = 4.5f;//indent from right side of screen private static final float installWidth = 12f;//multiplier of height private static Tab selectedTab = Tab.PLAY; private static int[] dragging = null; private static JPanel panel = new JPanel(); private static JFrame frame; private static final String name = "Thizzy'z Games"; private static final String root = System.getenv("APPDATA")+"\\"+name+"\\Launcher"; private static final String libraryRoot = System.getenv("APPDATA")+"\\"+name+"\\Libraries"; private static final Font font = addFont("simplelibrary-high-resolution.ttf"); private static final int OS_WINDOWS = 0; private static final int OS_SOLARIS = 1; private static final int OS_MACOSX = 2; private static final int OS_LINUX = 3; private static int OS = -1; private static int whichBitDepth = -1; private static int BIT_32 = 0; private static int BIT_64 = 1; public static void main(String[] args){ String OS = System.getenv("OS"); switch(OS){ case "Windows_NT": Main.OS = OS_WINDOWS; break; // Main.OS = OS_SOLARIS; // break; // Main.OS = OS_MACOSX; // break; // Main.OS = OS_LINUX; // break; default: Main.OS = JOptionPane.showOptionDialog(null, "Unrecognized OS \""+OS+"\"!\nPlease report this as a bug!\nIn the meantime, which OS are you currently running?", "Unrecognized Operating System", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, new String[]{"Windows", "Solaris", "Mac OSX", "Linux"}, "Windows"); if(Main.OS<0||Main.OS>3){ System.exit(0); } } String version = System.getenv("PROCESSOR_ARCHITECTURE"); switch(version){ case "x86": whichBitDepth = BIT_32; break; case "AMD64": whichBitDepth = BIT_64; break; default: whichBitDepth = JOptionPane.showOptionDialog(null, "Unrecognized processor architecture \""+version+"\"!\nPlease report this as a bug!.\nIn the meantime, Are you currently running 64 bit?", "Unrecognized Processor Architecture", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, new String[]{"No, treat it as a 32 bit system", "Yes, treat it as a 64 bit system"}, "Yes, treat it as a 64 bit system"); if(whichBitDepth<0||whichBitDepth>1){ System.exit(0); } } File launcherVersions = downloadFile("https://www.dropbox.com/s/rjdln5jt1z20zuw/versions.txt?dl=1", new File(root+"\\versions.txt"), false); if(launcherVersions.exists()){ try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(launcherVersions)))){ String newVersion = null; String[] updaterLink = reader.readLine().split("=", 3); String line = ""; while((line = reader.readLine())!=null){ if(line.trim().isEmpty())continue; if(VersionManager.getVersionID(line.split("=")[0])==-1){ newVersion = line; } } if(newVersion!=null){ File newLauncher = downloadFile(newVersion.split("=", 2)[1], new File(root+"\\launcher.jar"), false); File updater = downloadFile(updaterLink[2], new File(root+"\\updater "+updaterLink[1]+".jar"), true); if(updater.exists()){ startJava(new String[0], new String[]{Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath(), newLauncher.getAbsolutePath()}, updater); System.exit(0); } } }catch(URISyntaxException ex){ Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); }catch(IOException ex){} } frame = new JFrame(name+" Launcher "+VersionManager.currentVersion); frame.setUndecorated(true); Toolkit tk = Toolkit.getDefaultToolkit(); Dimension screenSize = tk.getScreenSize(); frame.setSize(WIDTH, HEIGHT); frame.setLocation((screenSize.width-WIDTH)/2, (screenSize.height-HEIGHT)/2); frame.add(panel); panel.setLayout(null); frame.setVisible(true); new Game(Tab.PLAY, "Planetary Protector", "Defend the earth against otherworldly attackers!", "https://www.dropbox.com/s/capgobag47srs17/versions.txt?dl=1", "https://www.dropbox.com/s/cv045rh295rjubk/libraries.txt?dl=1"); new Game(Tab.PLAY, "Pizza", "Make Pizza!", "https://www.dropbox.com/s/vfj58y5swhmcodj/versions.txt?dl=1", "https://www.dropbox.com/s/j9t64xx9c3y971b/libraries.txt?dl=1"); new Game(Tab.PLAY, "Amazing Machine", "Find your way through randomly generated mazes!", "https://www.dropbox.com/s/c4yj9a8ady6zmgw/versions.txt?dl=1", "https://www.dropbox.com/s/lwzts9tcxriqkj2/libraries.txt?dl=1"); new Game(Tab.PLAY, "Delubrian Invaders", "Explore and defend the galaxy!", "https://www.dropbox.com/s/17xbr20cq7m95oi/versions.txt?dl=1", "https://www.dropbox.com/s/t1dirgsm8ukg2cu/libraries.txt?dl=1"); new Game(Tab.TOOLS, "Geometry Printer", "Create and print geometric shapes!", "https://www.dropbox.com/s/3wu46gic6jwn2a2/versions.txt?dl=1", "https://www.dropbox.com/s/6dos3qgxkx8xlys/libraries.txt?dl=1"); rebuild(); } private static void rebuild(){ int width = frame.getWidth(); int height = frame.getHeight(); panel.setBounds(0, 0, width, height); panel.removeAll(); //<editor-fold defaultstate="collapsed" desc="Title Bar"> JPanel titleBar = new JPanel(){ @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(getForeground()); int height = (int)(getHeight()*titleHeight); g.setFont(font.deriveFont((float)height)); g.drawString(frame.getTitle(), 0, getHeight()/2+height/2); } }; titleBar.setLayout(null); panel.add(titleBar); titleBar.setBounds(0,0,width,40); titleBar.setBackground(Backgrounds.titleBar); titleBar.setForeground(Color.white); titleBar.addMouseListener(new MouseListener(){ @Override public void mouseClicked(MouseEvent e) {} @Override public void mousePressed(MouseEvent e){ if((frame.getExtendedState() & JFrame.MAXIMIZED_BOTH) == JFrame.MAXIMIZED_BOTH)return; dragging = new int[]{e.getX(), e.getY()}; } @Override public void mouseReleased(MouseEvent e){ dragging = null; } @Override public void mouseEntered(MouseEvent e){} @Override public void mouseExited(MouseEvent e){ if(dragging!=null){ frame.setLocation(e.getXOnScreen()-dragging[0], e.getYOnScreen()-dragging[1]); } } }); titleBar.addMouseMotionListener(new MouseMotionListener() { @Override public void mouseDragged(MouseEvent e) { if(dragging!=null){ frame.setLocation(e.getXOnScreen()-dragging[0], e.getYOnScreen()-dragging[1]); } } @Override public void mouseMoved(MouseEvent e) { } }); JPanel close = new JPanel(){ @Override protected void paintComponent(Graphics g) { g.setColor(getBackground()); g.fillRect(0, 0, width, height); g.setColor(getForeground()); int l = getWidth()/titleButtonSize; int r = getWidth()*(titleButtonSize-1)/titleButtonSize; g.drawLine(l, l, r, r); g.drawLine(r, l, l, r); } }; close.setBackground(Backgrounds.titleBar); close.setForeground(Color.white); close.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e){} @Override public void mousePressed(MouseEvent e){ frame.dispose(); } @Override public void mouseReleased(MouseEvent e){} @Override public void mouseEntered(MouseEvent e){ close.setForeground(Color.red); } @Override public void mouseExited(MouseEvent e){ close.setForeground(Color.white); } }); titleBar.add(close); close.setBounds(titleBar.getWidth()-titleBar.getHeight(), 0, titleBar.getHeight(), titleBar.getHeight()); JPanel maximize = new JPanel(){ @Override protected void paintComponent(Graphics g) { g.setColor(getBackground()); g.fillRect(0, 0, width, height); g.setColor(getForeground()); if((frame.getExtendedState() & JFrame.MAXIMIZED_BOTH) == JFrame.MAXIMIZED_BOTH){ int l = getWidth()/titleButtonSize; int r = getWidth()*(titleButtonSize-1)/titleButtonSize; int d = l/2; g.drawLine(l, l+d, l, r); g.drawLine(l, l+d, r-d, l+d); g.drawLine(r-d, l+d, r-d, r); g.drawLine(l, r, r-d, r); g.drawLine(l+d, l, r, l); g.drawLine(l+d, l, l+d, l+d); g.drawLine(r, l, r, r-d); g.drawLine(r-d, r-d, r, r-d); }else{ int l = getWidth()/titleButtonSize; int r = getWidth()*(titleButtonSize-1)/titleButtonSize; g.drawLine(l, l, r, l); g.drawLine(r, l, r, r); g.drawLine(l, r, r, r); g.drawLine(l, l, l, r); } } }; maximize.setBackground(Backgrounds.titleBar); maximize.setForeground(Color.lightGray); maximize.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e){} @Override public void mousePressed(MouseEvent e){ if((frame.getExtendedState() & JFrame.MAXIMIZED_BOTH) == JFrame.MAXIMIZED_BOTH) frame.setExtendedState(JFrame.NORMAL); else frame.setExtendedState(JFrame.MAXIMIZED_BOTH); rebuild(); } @Override public void mouseReleased(MouseEvent e){} @Override public void mouseEntered(MouseEvent e){ maximize.setForeground(Color.white); } @Override public void mouseExited(MouseEvent e){ maximize.setForeground(Color.lightGray); } }); titleBar.add(maximize); maximize.setBounds(titleBar.getWidth()-titleBar.getHeight()*2, 0, titleBar.getHeight(), titleBar.getHeight()); JPanel minimize = new JPanel(){ @Override protected void paintComponent(Graphics g) { g.setColor(getBackground()); g.fillRect(0, 0, width, height); g.setColor(getForeground()); int l = getWidth()/titleButtonSize; int r = getWidth()*(titleButtonSize-1)/titleButtonSize; g.drawLine(l, r, r, r); } }; minimize.setBackground(Backgrounds.titleBar); minimize.setForeground(Color.lightGray); minimize.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e){} @Override public void mousePressed(MouseEvent e){ frame.setExtendedState(frame.getExtendedState() | JFrame.ICONIFIED); } @Override public void mouseReleased(MouseEvent e){} @Override public void mouseEntered(MouseEvent e){ minimize.setForeground(Color.white); } @Override public void mouseExited(MouseEvent e){ minimize.setForeground(Color.lightGray); } }); titleBar.add(minimize); minimize.setBounds(titleBar.getWidth()-titleBar.getHeight()*3, 0, titleBar.getHeight(), titleBar.getHeight()); //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Content Panel"> JPanel contentPanel = new JPanel(); contentPanel.setLayout(null); panel.add(contentPanel); contentPanel.setBounds(0,titleBarHeight,width,height-titleBarHeight); contentPanel.setBackground(Backgrounds.contentPanel); //<editor-fold defaultstate="collapsed" desc="Header"> JPanel header = new JPanel(); header.setLayout(null); contentPanel.add(header); header.setBounds(0, 0, contentPanel.getWidth(), (int) (headerHeight*contentPanel.getHeight())); header.setBackground(Backgrounds.header); //<editor-fold defaultstate="collapsed" desc="Header Buttons"> Tab[] tabs = Tab.values(); int tabWidth = header.getWidth()/tabs.length; for(int i = 0; i<tabs.length; i++){ Tab tab = tabs[i]; JPanel button = new JPanel(){ @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); BufferedImage image = getImage("tabs/"+tab.name().toLowerCase()+".png"); if(image!=null){ int adjustedWidth = image.getWidth()*getHeight()/image.getHeight(); g.drawImage(image, getWidth()/2-adjustedWidth/2, 0, adjustedWidth, getHeight(), null); } g.setColor(getForeground()); int height = (int)(getHeight()*tabTextHeight); Font f = font.deriveFont((float)height); int width = (int) f.getStringBounds(tab.toString(), new FontRenderContext(null, false, false)).getWidth(); g.setFont(f); g.drawString(tab.toString(), getWidth()/2-width/2, getHeight()/2+height/2); } }; header.add(button); if(i==tabs.length-1){ button.setBounds(tabWidth*i, 0, header.getWidth()-(tabWidth*(tabs.length-1)), header.getHeight()); }else{ button.setBounds(tabWidth*i, 0, tabWidth, header.getHeight()); } button.setBackground(header.getBackground()); if(selectedTab==tab)button.setBackground(Backgrounds.selectedTab); button.setForeground(Color.white); button.addMouseListener(new MouseListener(){ @Override public void mouseClicked(MouseEvent e){} @Override public void mousePressed(MouseEvent e){ selectedTab = tab; rebuild(); } @Override public void mouseReleased(MouseEvent e){} @Override public void mouseEntered(MouseEvent e){ if(selectedTab!=tab){ button.setBackground(Backgrounds.mouseoverTab); } } @Override public void mouseExited(MouseEvent e){ if(selectedTab!=tab){ button.setBackground(Backgrounds.header); } } }); } //</editor-fold> //</editor-fold> if(selectedTab==Tab.SETTINGS){ JPanel installDir = new JPanel(){ @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); BufferedImage image; if(getForeground()==Color.white)image = getImage("icons/installMouseover.png"); else image = getImage("icons/install.png"); g.drawImage(image, 0, 0, getWidth(), getHeight(), null); g.setColor(getForeground()); int height = (int) (buttonSize*contentPanel.getHeight()*.9f); Font f = font.deriveFont((float)height); int width = (int) f.getStringBounds("Open Install Directory", new FontRenderContext(null, false, false)).getWidth(); g.setFont(f); g.drawString("Open Install Directory", getWidth()/2-width/2, getHeight()/2+height/2); } }; contentPanel.add(installDir); int size = (int) (contentPanel.getHeight()*buttonSize); installDir.setBounds((int) (contentPanel.getWidth()-size*(playIndent+installWidth)), contentPanel.getHeight()/2-size/2, (int) (size*installWidth), size); installDir.setBackground(Backgrounds.contentPanel); installDir.setForeground(new Color(245,245,245)); installDir.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e){} @Override public void mousePressed(MouseEvent e){ try{ Desktop.getDesktop().open(new File(System.getenv("APPDATA")+"\\"+name)); }catch(IOException ex){ } } @Override public void mouseReleased(MouseEvent e){} @Override public void mouseEntered(MouseEvent e){ installDir.setForeground(Color.white); } @Override public void mouseExited(MouseEvent e){ installDir.setForeground(new Color(245,245,245)); } }); }else{ //<editor-fold defaultstate="collapsed" desc="Game List"> if(!selectedTab.games.isEmpty()){ int gameWidth = width/4; int gameHeight = (contentPanel.getHeight()-header.getHeight())/selectedTab.games.size(); for(int i = 0; i<selectedTab.games.size(); i++){ Game game = selectedTab.games.get(i); //<editor-fold defaultstate="collapsed" desc="Game Title"> JPanel gameTitle = new JPanel(){ @Override protected void paintComponent(Graphics g){ super.paintComponent(g); g.setColor(getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); BufferedImage image = getImage("games/"+game.name.toLowerCase().replace(" ", "_")+".png"); if(image!=null){ int adjustedWidth = image.getWidth()*getHeight()/image.getHeight(); g.drawImage(image, getWidth()/2-adjustedWidth/2, 0, adjustedWidth, getHeight(), null); } g.setColor(getForeground()); int height = (int) (textSize*contentPanel.getHeight()); Font f = font.deriveFont((float)height); int width = (int) f.getStringBounds(game.name, new FontRenderContext(null, false, false)).getWidth(); g.setFont(f); g.drawString(game.name, getWidth()/2-width/2, getHeight()/2+height/2); if(game.currentVersion!=null){ width = (int) f.getStringBounds(game.currentVersion, new FontRenderContext(null, false, false)).getWidth(); g.drawString(game.currentVersion, getWidth()/2-width/2, getHeight()/2+height*3/2); } } }; contentPanel.add(gameTitle); if(i==selectedTab.games.size()-1){ gameTitle.setBounds(0, header.getHeight()+gameHeight*i, gameWidth, contentPanel.getHeight()-header.getHeight()-(gameHeight*(selectedTab.games.size()-1))); }else{ gameTitle.setBounds(0, header.getHeight()+gameHeight*i, gameWidth, gameHeight); } gameTitle.setBackground(Backgrounds.game); gameTitle.setForeground(Color.white); //</editor-fold> if(game.getStatus()==Status.NOT_INSTALLED){ JPanel download = new JPanel(){ @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); BufferedImage image; if(getForeground()==Color.white)image = getImage("icons/downloadMouseover.png"); else image = getImage("icons/download.png"); g.drawImage(image, 0, 0, getWidth(), getHeight(), null); } }; contentPanel.add(download); int size = (int) (contentPanel.getHeight()*buttonSize); download.setBounds((int) (contentPanel.getWidth()-size*(buttonIndent+1)), gameTitle.getY()+gameTitle.getHeight()/2-size/2, size, size); download.setBackground(Backgrounds.contentPanel); download.setForeground(Color.lightGray); download.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e){} @Override public void mousePressed(MouseEvent e){ game.download(); } @Override public void mouseReleased(MouseEvent e){} @Override public void mouseEntered(MouseEvent e){ download.setForeground(Color.white); } @Override public void mouseExited(MouseEvent e){ download.setForeground(Color.lightGray); } }); }else{ if(game.getStatus()==Status.DOWNLOADED){ JPanel play = new JPanel(){ @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); BufferedImage image; if(getForeground()==Color.white)image = getImage("icons/playMouseover.png"); else image = getImage("icons/play.png"); g.drawImage(image, 0, 0, getWidth(), getHeight(), null); g.setColor(getForeground()); int height = (int) (buttonSize*contentPanel.getHeight()*.9f); Font f = font.deriveFont((float)height); int width = (int) f.getStringBounds("Play", new FontRenderContext(null, false, false)).getWidth(); g.setFont(f); g.drawString("Play", getWidth()/2-width/2, getHeight()/2+height/2); } }; contentPanel.add(play); int size = (int) (contentPanel.getHeight()*buttonSize); play.setBounds((int) (contentPanel.getWidth()-size*(playIndent+playWidth)), gameTitle.getY()+gameTitle.getHeight()/2-size/2, (int) (size*playWidth), size); play.setBackground(Backgrounds.contentPanel); play.setForeground(new Color(245,245,245)); play.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e){} @Override public void mousePressed(MouseEvent e){ game.play(); } @Override public void mouseReleased(MouseEvent e){} @Override public void mouseEntered(MouseEvent e){ play.setForeground(Color.white); } @Override public void mouseExited(MouseEvent e){ play.setForeground(new Color(245,245,245)); } }); if(game.hasUpdate()){ JPanel update = new JPanel(){ @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); BufferedImage image; if(getForeground()==Color.white)image = getImage("icons/updateMouseover.png"); else image = getImage("icons/update.png"); g.drawImage(image, 0, 0, getWidth(), getHeight(), null); } }; contentPanel.add(update); size = (int) (contentPanel.getHeight()*buttonSize); update.setBounds((int) (contentPanel.getWidth()-size*(buttonIndent+1)), gameTitle.getY()+gameTitle.getHeight()/2-size/2, size, size); update.setBackground(Backgrounds.contentPanel); update.setForeground(Color.lightGray); update.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e){} @Override public void mousePressed(MouseEvent e){ game.update(); } @Override public void mouseReleased(MouseEvent e){} @Override public void mouseEntered(MouseEvent e){ update.setForeground(Color.white); } @Override public void mouseExited(MouseEvent e){ update.setForeground(Color.lightGray); } }); } } } } } //</editor-fold> } //</editor-fold> frame.repaint(); } private static class Backgrounds{ private static final Color contentPanel = new Color(130,130,130); private static final Color titleBar = new Color(90,90,90); private static final Color header = new Color(110,111,112); private static final Color selectedTab = new Color(100, 101, 102); private static final Color mouseoverTab = new Color(120, 121, 122); private static final Color game = new Color(120, 120, 120); // private static final Color selectedGame = new Color(120, 121, 122); // private static final Color mouseoverGame = new Color(140, 141, 142); } private static enum Tab{ PLAY,TOOLS,SETTINGS; private final ArrayList<Game> games = new ArrayList<>(); @Override public String toString(){ return name().charAt(0)+name().substring(1).toLowerCase(); } } private static final HashMap<String, BufferedImage> images = new HashMap<>(); private static BufferedImage getImage(String path){ if(images.containsKey(path))return images.get(path); try { if(new File("nbproject").exists()){ images.put(path, ImageIO.read(new File("src\\textures\\"+path.replace("/", "\\")))); }else{ JarFile jar = new JarFile(new File(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath().replace("%20", " "))); Enumeration enumEntries = jar.entries(); while(enumEntries.hasMoreElements()){ JarEntry file = (JarEntry)enumEntries.nextElement(); System.out.println(file.getName()); if(file.getName().equals("textures/"+path.replace("\\", "/"))){ images.put(path, ImageIO.read(jar.getInputStream(file))); break; } } } } catch (IOException ex) { System.err.println("Image not found: "+path); images.put(path, null); } return images.get(path); } private static Font addFont(String path){ try { if(new File("nbproject").exists()){ return Font.createFont(Font.TRUETYPE_FONT, new File("src\\fonts\\"+path.replace("/", "\\"))); }else{ JarFile jar = new JarFile(new File(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath().replace("%20", " "))); Enumeration enumEntries = jar.entries(); while(enumEntries.hasMoreElements()){ JarEntry file = (JarEntry)enumEntries.nextElement(); System.out.println(file.getName()); if(file.getName().equals("fonts/"+path.replace("\\", "/"))){ return Font.createFont(Font.TRUETYPE_FONT, jar.getInputStream(file)); } } } } catch (IOException | FontFormatException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } return null; } private static class Game{ private final String name; private final String gameRoot; private Status status; private final String description; private final String versionsURL; private final String librariesURL; private final ArrayList<String> versions = new ArrayList<>(); private final ArrayList<String> libraries = new ArrayList<>(); private String currentVersion; private Game(Tab tab, String name, String description, String versionsURL, String librariesURL){ this.name = name; gameRoot = root+"\\"+name; status = getJarfile().exists()?Status.DOWNLOADED:null; this.description = description; this.versionsURL = versionsURL; this.librariesURL = librariesURL; tab.games.add(this); File version = new File(gameRoot+"\\version.txt"); try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(version)))) { currentVersion = reader.readLine(); }catch(IOException ex){ } new Thread(()->{ File versionsFile = downloadFile(versionsURL, new File(gameRoot+"\\versions.txt"), false); File librariesFile = downloadFile(librariesURL, new File(gameRoot+"\\libraries.txt"), false); if(versionsFile!=null){ try{ BufferedReader versions = new BufferedReader(new InputStreamReader(new FileInputStream(versionsFile))); String line; while((line = versions.readLine())!=null){ if(!line.isEmpty())this.versions.add(line); } versions.close(); }catch(IOException ex){ versionsFile = null; } } if((versionsFile!=null&&librariesFile!=null&&!versions.isEmpty())||status==Status.DOWNLOADED){ if(status==null)status = Status.NOT_INSTALLED; rebuild(); } }, name+" Discovery Thread").start(); } private Status getStatus(){ return status; } private boolean hasUpdate(){ if(currentVersion==null)return false; if(versions.isEmpty())return false; return !versions.get(versions.size()-1).startsWith(currentVersion+"="); } private void download(){ Thread t = new Thread(() -> { status = Status.DOWNLOADING; rebuild(); downloadFile(versions.get(versions.size()-1).split("=", 2)[1], getJarfile(), false); File version = new File(gameRoot+"\\version.txt"); if(version.exists())version.delete(); version.getParentFile().mkdirs(); try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(version)))) { String ver = versions.get(versions.size()-1).split("=")[0]; writer.write(ver); currentVersion = ver; }catch(IOException ex){ Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } try { File currentLibraries = new File(gameRoot+"\\currentLibraries.txt"); currentLibraries.delete(); Files.copy(new File(gameRoot+"\\libraries.txt").toPath(), currentLibraries.toPath()); if(!verifyLibraries()){ JOptionPane.showMessageDialog(null, "Failed to verify dependencies!", "Download Failed", JOptionPane.OK_OPTION); } } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } status = Status.DOWNLOADED; rebuild(); }, name+" Download Thread"); t.start(); } private void update(){ download(); } private File getJarfile(){ return new File(gameRoot+"\\"+name+".jar"); } private void findLibraries(){ try{ if(libraries.isEmpty()){ File currentLibraries = new File(gameRoot+"\\currentLibraries.txt"); BufferedReader libraries = new BufferedReader(new InputStreamReader(new FileInputStream(currentLibraries))); String line; while((line = libraries.readLine())!=null){ if(!line.isEmpty())this.libraries.add(line); } libraries.close(); } } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } private boolean verifyLibraries(){ return verifyLibraries(null); } private boolean verifyLibraries(ArrayList<File> files){ if(files==null)files = new ArrayList<>(); findLibraries(); for(String lib : libraries){ lib = lib.trim(); if(lib.isEmpty())continue; if(lib.equalsIgnoreCase("LWJGL")){ String[][] nativesPaths = { {"https://dl.dropboxusercontent.com/s/1nt1g7ui7p4eb54/windows32natives.zip?dl=1&token_hash=AA<PASSWORD>", "https://dl.dropboxusercontent.com/s/y41peavuls3ptzu/windows64natives.zip?dl=1&token_hash=<PASSWORD>"}, {"https://dl.dropboxusercontent.com/s/h4z3j2pspuos15l/solaris32natives.zip?dl=1&token_hash=AA<PASSWORD>", "https://dl.dropboxusercontent.com/s/vq3x3n81x0qvc3u/solaris64natives.zip?dl=1&token_hash=AA<PASSWORD>"}, {"https://dl.dropboxusercontent.com/s/ljvgoccqz33bcq1/macosx32natives.zip?dl=1&token_hash=<PASSWORD>", null}, {"https://dl.dropboxusercontent.com/s/nfv4ra6n68lna9n/linux32natives.zip?dl=1&token_<PASSWORD>=<PASSWORD>", "https://dl.dropboxusercontent.com/s/rp6uhdmec7697ty/linux64natives.zip?dl=1&token_hash=<PASSWORD>"} }; String[] osPaths = nativesPaths[OS]; if(!downloadLibrary("https://dl.dropboxusercontent.com/s/p7v72lix4gl96co/lwjgl.jar?dl=1&token_<PASSWORD>=AAG<PASSWORD>1_xwgVjKoE8FkKXMaWOfpj5cau1UuWKZlA", files))return false; if(!downloadLibrary("https://dl.dropboxusercontent.com/s/9ylaq5w5vzj1lgi/jinput.jar?dl=1&token_hash=<KEY>", files))return false; if(!downloadLibrary("https://dl.dropboxusercontent.com/s/fog6w5pcxqf4zd9/lwjgl_util.jar?dl=1&token_<PASSWORD>=<KEY>", files))return false; if(!downloadLibrary("https://dl.dropboxusercontent.com/s/60en1x8in11leqn/lzma.jar?dl=1&token_<PASSWORD>=<PASSWORD>", files))return false; File bit32 = downloadFile(osPaths[BIT_32], new File(libraryRoot+"\\natives32.zip"), true); File bit64 = whichBitDepth==BIT_64?downloadFile(osPaths[BIT_64], new File(libraryRoot+"\\natives64.zip"), true):null; File nativesDir = new File(libraryRoot+"\\natives"); if(bit32==null||(whichBitDepth==BIT_64&&bit64==null&&osPaths[BIT_64]!=null))return false; if(!nativesDir.exists()){ extractFile(bit32, nativesDir); if(bit64!=null){ extractFile(bit64, nativesDir); } } }else if(lib.toLowerCase().startsWith("simplibext")){ String version = lib.substring(10).trim(); try{ File simpLibExtendedVersions = downloadFile("https://www.dropbox.com/s/7k4ri81to8hc9n2/versions.dat?dl=1", new File(libraryRoot+"\\simplibext.versions"), false); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(simpLibExtendedVersions))); ArrayList<String> versions = new ArrayList<>(); HashMap<String, String> simpLibExtended = new HashMap<>(); String line; while((line = reader.readLine())!=null){ if(line.isEmpty())continue; versions.add(line.split("=", 2)[0]); simpLibExtended.put(line.split("=", 2)[0], line.split("=", 2)[1]); } reader.close(); if(!versions.contains(version)){ System.err.println("Unknown Simplelibrary_extended version "+version+"! Downloading latest version"); version = versions.get(versions.size()-1); } File f = downloadFile(simpLibExtended.get(version), new File(libraryRoot+"\\Simplelibrary_extended "+version+".jar"), true); files.add(f); if(!f.exists())return false; simpLibExtendedVersions.delete(); }catch(IOException ex){ File f = new File(libraryRoot+"\\Simplelibrary_extended "+version+".jar"); files.add(f); if(!f.exists())return false; } }else if(lib.toLowerCase().startsWith("simplib")){ String version = lib.substring(7).trim(); try{ File simplibVersions = downloadFile("https://www.dropbox.com/s/as5y1ik7gb8gp6k/versions.dat?dl=1", new File(libraryRoot+"\\simplib.versions"), false); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(simplibVersions))); ArrayList<String> versions = new ArrayList<>(); HashMap<String, String> simplib = new HashMap<>(); String line; while((line = reader.readLine())!=null){ if(line.isEmpty())continue; versions.add(line.split("=", 2)[0]); simplib.put(line.split("=", 2)[0], line.split("=", 2)[1]); } reader.close(); if(!versions.contains(version)){ System.err.println("Unknown simplelibrary version "+version+"! Downloading latest version"); version = versions.get(versions.size()-1); } File f = downloadFile(simplib.get(version), new File(libraryRoot+"\\Simplelibrary "+version+".jar"), true); files.add(f); if(!f.exists())return false; simplibVersions.delete(); }catch(IOException ex){ File f = new File(libraryRoot+"\\Simplelibrary "+version+".jar"); files.add(f); if(!f.exists())return false; } }else if(lib.endsWith("?dl=1")){ if(!downloadLibrary(lib, files))return false; } } return true; } private boolean downloadLibrary(String link, ArrayList<File> files){ String filename = link.split("\\Q?")[0]; while(filename.contains("/"))filename = filename.substring(filename.indexOf("/")+1); File f = downloadFile(link, new File(libraryRoot+"\\"+filename), true); files.add(f); return f.exists(); } private void play(){ new Thread(() -> { status = Status.PLAYING; rebuild(); ArrayList<File> files = new ArrayList<>(); if(!verifyLibraries(files)){ JOptionPane.showMessageDialog(null, "Failed to verify dependencies!", "Startup Failed", JOptionPane.OK_OPTION); status = Status.DOWNLOADED; rebuild(); return; } String[] additionalClasspathElements = new String[files.size()]; for(int i = 0; i<files.size(); i++){ additionalClasspathElements[i] = files.get(i).getAbsolutePath(); } ArrayList<String> theargs = new ArrayList<>(); theargs.add(0, "Skip Dependencies"); boolean lwjgl = false; ArrayList<String> vmArgs = new ArrayList<>(); for(String lib : libraries){ if(lib.equalsIgnoreCase("lwjgl"))vmArgs.add("-Djava.library.path="+new File(libraryRoot+"\\natives").getAbsolutePath()); }try{ final Process p = run(vmArgs.toArray(new String[vmArgs.size()]), theargs.toArray(new String[theargs.size()]), additionalClasspathElements, getJarfile()); new Thread(){ public void run(){ BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; try{ while((line=in.readLine())!=null){ System.out.println(line); } }catch(IOException ex){ throw new RuntimeException(ex); } } }.start(); new Thread(){ public void run(){ BufferedReader in = new BufferedReader(new InputStreamReader(p.getErrorStream())); String line; try{ while((line=in.readLine())!=null){ System.err.println(line); } }catch(IOException ex){ throw new RuntimeException(ex); } } }.start(); Thread t = new Thread(){ public void run(){ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(p.getOutputStream()); String line; try{ while((line=in.readLine())!=null){ out.println(line); out.flush(); } }catch(IOException ex){ throw new RuntimeException(ex); } } }; t.setDaemon(true); t.start(); }catch(URISyntaxException | IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } status = Status.DOWNLOADED; rebuild(); }, "Startup Thread").start(); } } private static enum Status{ DOWNLOADING,DOWNLOADED,NOT_INSTALLED,PLAYING; } private static File downloadFile(String link, File destinationFile, boolean keep){ if(true){ synchronized(link){ destinationFile.getParentFile().mkdirs(); if(keep&&destinationFile.exists())return destinationFile; try { Files.copy(new URL(link).openStream(), destinationFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException ex) { return destinationFile; } return destinationFile; } } if(destinationFile.exists()&&keep)return destinationFile; if(link==null){ return destinationFile; } File old = new File(destinationFile.getParentFile(), destinationFile.getName()+".old"); if(old.exists())old.delete(); if(destinationFile.exists()){ destinationFile.renameTo(old); destinationFile.delete(); } destinationFile.getParentFile().mkdirs(); try { URL url = new URL(link); int fileSize; URLConnection connection = url.openConnection(); connection.setDefaultUseCaches(false); if ((connection instanceof HttpURLConnection)) { ((HttpURLConnection)connection).setRequestMethod("HEAD"); int code = ((HttpURLConnection)connection).getResponseCode(); if (code / 100 == 3) { if(old.exists()){ if(destinationFile.exists())destinationFile.delete(); if(old.renameTo(destinationFile)){ old.delete(); return destinationFile; } old.delete(); } return null; } } fileSize = connection.getContentLength(); byte[] buffer = new byte[65535]; int unsuccessfulAttempts = 0; int maxUnsuccessfulAttempts = 3; boolean downloadFile = true; while (downloadFile) { downloadFile = false; URLConnection urlconnection = url.openConnection(); if ((urlconnection instanceof HttpURLConnection)) { urlconnection.setRequestProperty("Cache-Control", "no-cache"); urlconnection.connect(); } String targetFile = destinationFile.getName(); FileOutputStream fos; int downloadedFileSize; try (InputStream inputstream=getRemoteInputStream(targetFile, urlconnection)) { fos=new FileOutputStream(destinationFile); downloadedFileSize=0; int read; while ((read = inputstream.read(buffer)) != -1) { fos.write(buffer, 0, read); downloadedFileSize += read; } } fos.close(); if (((urlconnection instanceof HttpURLConnection)) && ((downloadedFileSize != fileSize) && (fileSize > 0))){ unsuccessfulAttempts++; if (unsuccessfulAttempts < maxUnsuccessfulAttempts){ downloadFile = true; }else{ throw new Exception("failed to download "+targetFile); } } } return destinationFile; }catch (Exception ex){ if(old.exists()){ if(destinationFile.exists())destinationFile.delete(); if(old.renameTo(destinationFile)){ old.delete(); return destinationFile; } old.delete(); } return null; } } private static InputStream getRemoteInputStream(String currentFile, final URLConnection urlconnection) throws Exception { final InputStream[] is = new InputStream[1]; for (int j = 0; (j < 3) && (is[0] == null); j++) { Thread t = new Thread() { public void run() { try { is[0] = urlconnection.getInputStream(); }catch (IOException localIOException){} } }; t.setName("FileDownloadStreamThread"); t.start(); int iterationCount = 0; while ((is[0] == null) && (iterationCount++ < 5)){ try { t.join(1000L); } catch (InterruptedException localInterruptedException) { } } if (is[0] != null){ continue; } try { t.interrupt(); t.join(); } catch (InterruptedException localInterruptedException1) { } } if (is[0] == null) { throw new Exception("Unable to download "+currentFile); } return is[0]; } private static synchronized void extractFile(File fromZip, File toDir){ if(!fromZip.exists()){ return; } toDir.mkdirs(); try(ZipInputStream in = new ZipInputStream(new FileInputStream(fromZip))){ ZipEntry entry; while((entry = in.getNextEntry())!=null){ File destFile = new File(toDir.getAbsolutePath()+"\\"+entry.getName().replaceAll("/", "\\")); delete(destFile); try(FileOutputStream out = new FileOutputStream(destFile)){ byte[] buffer = new byte[1024]; int read = 0; while((read=in.read(buffer))>=0){ out.write(buffer, 0, read); } } } }catch(FileNotFoundException ex){ throw new UnsupportedOperationException(ex); }catch(IOException ex){ throw new RuntimeException(ex); } } private static void delete(File file){ if(!file.exists()){ return; } if(file.isDirectory()){ File[] files = file.listFiles(); if(files!=null){ for(File afile : files){ delete(afile); } } } file.delete(); } /** * Restarts the program. This method will return normally if the program was properly restarted or throw an exception if it could not be restarted. * @param vmArgs The VM arguments for the new instance * @param applicationArgs The application arguments for the new instance * @param additionalFiles Any additional files to include in the classpath * @param jarfile The Jar file to run * @param mainClass The program's main class. The new instance is started with this as the specified main class. * @throws URISyntaxException if a URI cannot be created to obtain the filepath to the jarfile * @throws IOException if Java is not in the PATH environment variable */ private static Process run(String[] vmArgs, String[] applicationArgs, String[] additionalFiles, File jarfile) throws URISyntaxException, IOException{ ArrayList<String> params = new ArrayList<>(); params.add("java"); params.addAll(Arrays.asList(vmArgs)); params.add("-cp"); String filepath = jarfile.getAbsolutePath(); for(String str : additionalFiles){ filepath+=";"+str; } params.add(filepath); params.add(getMainClass(jarfile)); params.addAll(Arrays.asList(applicationArgs)); System.out.println(params); ProcessBuilder builder = new ProcessBuilder(params); return builder.start(); } private static String getMainClass(File f){ try(ZipFile j = new ZipFile(f);BufferedReader in = new BufferedReader(new InputStreamReader(j.getInputStream(j.getEntry("META-INF/MANIFEST.MF"))))){ ArrayList<String> n = new ArrayList<>(); String g = null; while((g=in.readLine())!=null){ if(g.startsWith("Main-Class:")){ return g.split("\\Q:",2)[1].trim(); } } }catch(Throwable t){ throw new RuntimeException(t); } return null; } /** * Starts the requested Java application the program. This method will return normally if the program was properly restarted or throw an exception if it could not be restarted. * @param vmArgs The VM arguments for the new instance * @param applicationArgs The application arguments for the new instance * @param file The program file. The new instance is started with this as the specified main class. * @throws URISyntaxException if a URI cannot be created to obtain the filepath to the jarfile * @throws IOException if Java is not in the PATH environment variable */ private static Process startJava(String[] vmArgs, String[] applicationArgs, File file) throws URISyntaxException, IOException{ ArrayList<String> params = new ArrayList<>(); params.add("java"); params.addAll(Arrays.asList(vmArgs)); params.add("-jar"); params.add(file.getAbsolutePath()); params.addAll(Arrays.asList(applicationArgs)); ProcessBuilder builder = new ProcessBuilder(params); return builder.start(); } }<file_sep>package launcher; import java.util.ArrayList; /** * A version manager class, created to make version management easy. * @author Bryan */ public class VersionManager{ /** * The current version (This version) * @since Public Acceptance Text 1 (Initial Release) */ public static final String currentVersion; /** * List of all recognized versions. * @since Public Acceptance Text 1 (Initial Release) */ private static final ArrayList<String> versions = new ArrayList<>(); /** * The earliest version that the current version has back compatibility for. * @since Public Acceptance Text 1 (Initial Release) */ private static String backCompatibleTo; static{ addVersion("updater");//This is the updater, not the launcher; ignoring breakBackCompatability(); addVersion("1.0"); addVersion("1.1"); currentVersion = versions.get(versions.size()-1); } /** * Adds a version to the versions list. Used only in the static initializer of this class. * @param string The name of the version to add * @since Public Acceptance Text 1 (Initial Release) */ private static void addVersion(String string){ if(versions.contains(string)){ throw new IllegalArgumentException("Cannot add same version twice!"); } versions.add(string); if(breakBackCompatibility){ breakBackCompatibility = false; backCompatibleTo = getVersion(versions.size()-1); } } /** * Gets the version ID for the specified String version * @param version The version to ID * @return The version ID (-1 if <code>version</code> is not a valid version) * @since Public Acceptance Text 1 (Initial Release) */ public static int getVersionID(String version){ return versions.indexOf(version); } /** * Gets the String version for the specified version ID * @param ID the version ID * @return The String version * @throws IndexOutOfBoundsException if the ID is not a valid version ID * @since Public Acceptance Text 1 (Initial Release) */ public static String getVersion(int ID){ return versions.get(ID); } private static boolean breakBackCompatibility; /** * Informs the version manager that there is no back compatibility. * Sets <code>backCompatibleTo</code> to the next index in <code>versions</code> * Used only in the static initializer of this class. * @since Public Acceptance Text 1 (Initial Release) */ private static void breakBackCompatability(){ breakBackCompatibility = true; } /** * Checks if the system has back compatibility for the specified version ID * @param versionID The version ID to check * @return If back compatibility exists for the specified version ID * @since Public Acceptance Text 1 (Initial Release) */ public static boolean isCompatible(int versionID){ if(backCompatibleTo==null){ breakBackCompatability(); } return getVersionID(backCompatibleTo)<=versionID; } public static boolean isCompatible(String version){ return isCompatible(getVersionID(version)); } } <file_sep>All libraries are covered under their respective licenses
3d2a14fae344da31b8314e345d9dd3ea91f2f3bb
[ "Markdown", "Java" ]
3
Java
ThizThizzyDizzy/thizzyz-games-launcher
885eff98b9ce75db80ef9b124feebdf1dbb44026
d14152477c847e583dcb3faf717dbbd809b77625
refs/heads/master
<file_sep>#!/usr/bin/env python # -*- coding: utf8 -*- # base of Read.py import RPi.GPIO as GPIO import MFRC522 import signal import time import sys import os import subprocess from random import randint # SoC als Pinreferenz waehlen GPIO.setmode(GPIO.BOARD) GPIO.cleanup() # Pin 24 vom SoC als Input deklarieren und Pull-Down Widerstand aktivieren GPIO.setup(11, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) GPIO.setup(12, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) GPIO.setup(13, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) GPIO.setup(15, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) GPIO.setup(16, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) GPIO.setup(29, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) GPIO.setup(31, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) GPIO.setup(32, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) GPIO.setup(33, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) GPIO.setup(35, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) GPIO.setup(36, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) GPIO.setup(37, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) GPIO.setup(38, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) GPIO.setup(40, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) # ISR def intShutdown(channel): os.system('shutdown -h now') # ISR def intVolDec(channel): os.system('mpc volume -5') # ISR def intVolInc(channel): os.system('mpc volume +5') # ISR def intPlay(channel): os.system('mpc play 1') # ISR def intStop(channel): os.system('mpc stop') # Interrupt Event hinzufuegen. Pin x, auf steigende Flanke reagieren und ISR "Interrupt" deklarieren GPIO.add_event_detect(11, GPIO.RISING, callback = intShutdown, bouncetime = 400) GPIO.add_event_detect(16, GPIO.RISING, callback = intVolDec, bouncetime = 400) GPIO.add_event_detect(29, GPIO.RISING, callback = intVolInc, bouncetime = 400) GPIO.add_event_detect(38, GPIO.RISING, callback = intPlay, bouncetime = 400) GPIO.add_event_detect(40, GPIO.RISING, callback = intStop, bouncetime = 400) continue_reading = True v_cont = 1 # read only one UID or =1 continue reading v_hex = 1 # UID as decimal or hexal v_deb = 0 # additional information cardSN = "" cardSNold = "" count_error = 0 # Capture SIGINT for cleanup when the script is aborted def end_read(signal,frame): global continue_reading continue_reading = False if v_deb == 1: print " Ctrl+C captured, ending read." # Hook the SIGINT signal.signal(signal.SIGINT, end_read) # Create an object of the class MFRC522 MIFAREReader = MFRC522.MFRC522() mpc = { "040A3BF1F52580" : "Bibi40.mp3", "36FA6A90" : "Bibi", "044F3E12062280" : "Drachen1.mp3", "3B2A41D5":"Drachen2.mp3" } mpcpre = "mpc volume 65; mpc clear; mpc " mpcsuf = ";mpc play" while continue_reading: (status,TagType,CardTypeRec) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL) if status == MIFAREReader.MI_OK: cardTypeNo = CardTypeRec[1]*256+CardTypeRec[0] (status,uid,uidData) = MIFAREReader.MFRC522_Anticoll() if status == MIFAREReader.MI_OK: count_error = 0 cardType = "" cardSN = MIFAREReader.list2HexStr(uidData) if cardSNold == cardSN: # wait one sec. before next read will be started time.sleep(5) else: print cardSN ################## Play ################## if "mp3" not in mpc[cardSN]: # Handle m3u # cat /var/lib/mpd/playlists/Bibi.m3u | wc -l command = "cat /var/lib/mpd/playlists/"+mpc[cardSN]+".m3u | wc -l" print "command: " + command lineCount = subprocess.check_output(command, shell=True) random = randint(1, int(lineCount)) # get random Interger between 1 and playlist length os.system(mpcpre+"load "+mpc[cardSN]+mpcsuf+" "+str(random)); # play random position in playlist else: # Handle singe mp3 os.system(mpcpre+"add "+mpc[cardSN]+mpcsuf); ################## Play ################## cardSNold = cardSN else: cardSNold = "" else: # Card read error / no Card found if count_error>4: cardSNold = "" count_error = count_error+1 if v_cont == 0: # once must be readed if len(cardSN)>1: continue_reading = False GPIO.cleanup()
d77110708792d27fafc6b4f7147d4602aed2ec3d
[ "Python" ]
1
Python
SaschaJohn/rfidBox
7e0e7755bb2aad734cf70e6e1d1d900f182f5828
13f276bf3905bcd8d2b21613929b0bcd1d8878ce
refs/heads/main
<file_sep>export const color = { fullSliderBar: 'hsl(174, 77%, 80%)', sliderBackground: 'hsl(174, 86%, 45%)', discountBackground: 'hsl(14,92%, 95%)', discountText: 'hsl(15,100%,70%)', ctaText: 'hsl(226,100%,87%)', pricingComponentBackground: 'hsl(0,0%,100%)', mainBackground: 'hsl(230, 100%, 99%)', emptySliderBar: 'hsl(224,65%,95%)', toggleBackground: 'hsl(223,50%,87%)', text: 'hsl(225, 20%, 60%)', textCTABackground: 'hsl(227,35%,25%)', }; export const font = { size: '.75rem', regular: '600', bold: '800' } <file_sep>import React from 'react'; import styled from 'styled-components'; import { color } from '../Styles'; const ToggleSwitch = ({ setToggle }) => { return ( <Container> <label className='switch'> <input type='checkbox' onClick={(e) => setToggle(e.target.checked)} /> <span className='slider round'></span> </label> </Container> ); }; export default ToggleSwitch; const Container = styled.div` .switch { position: relative; display: inline-block; width: 55px; height: 18px; margin: 0 1rem; } .switch input { opacity: 0; width: 0; height: 0; } .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; -webkit-transition: 0.4s; transition: 0.4s; } .slider:before { position: absolute; content: ''; height: 13px; width: 13px; left: 6px; bottom: 3px; background-color: white; -webkit-transition: 0.4s; transition: 0.4s; } input:checked + .slider { background-color: ${color.sliderBackground}; } input:focus + .slider { box-shadow: 0 0 1px #2196f3; } input:checked + .slider:before { -webkit-transform: translateX(26px); -ms-transform: translateX(26px); transform: translateX(26px); } .slider.round { border-radius: 34px; background-color: ${color.toggleBackground}; } .slider.round:before { border-radius: 50%; } `; <file_sep>import React from 'react'; import styled from 'styled-components'; import { color } from '../Styles'; import circles from '../images/pattern-circles.svg'; const Heading = () => { return ( <Header> <h1> Simple, traffic-based pricing</h1> <h2>Sign-up for our 30-day trial. No credit card required.</h2> </Header> ); }; export default Heading; const Header = styled.div` display: flex; flex-direction: column; justify-content: center; text-align: center; height: 9.5rem; margin-bottom: 3rem; background: url(${circles}) no-repeat top; h1 { color: ${color.textCTABackground}; font-size: 1.8rem; margin-bottom: .5rem; } h2 { color: ${color.text}; font-size: .9rem; } `;
534e722838029f2a8d4324eb5ab726b606d5d697
[ "JavaScript" ]
3
JavaScript
cconner57/React-Interactive-Pricing-Component
6a0f7384869453b9e973a7f20b8366f5715138b2
adad85c56ef96e512857351db758526c74785d87
refs/heads/master
<repo_name>nguyenhongnhatlam/BooksShopOnline<file_sep>/Models/BookDatabaseInitializer .cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; namespace BooksShopOnline.Models { public class BookDatabaseInitializer : DropCreateDatabaseAlways<BookContext> { protected override void Seed(BookContext context) { GetCategories().ForEach(c => context.Categories.Add(c)); GetBooks().ForEach(p => context.Books.Add(p)); } private static List<Category> GetCategories() { var categories = new List<Category> { new Category { CategoryID = 1, CategoryName = "Hàng Mẫu" }, new Category { CategoryID = 2, CategoryName = "Hàng Mới" }, new Category { CategoryID = 3, CategoryName = "Hàng Giảm Giá" }, new Category { CategoryID = 4, CategoryName = "Hàng tặng" } }; return categories; } private static List<Book> GetBooks() { var books = new List<Book> { //book 1 new Book { BookID = 1, BookName = "combo apple", Description = "Gồm laptop,Máy in, Tv, ipad,...", ImagePath="hinh1.jpg", UnitPrice = 100.000f, CategoryID = 1 }, //book 2 new Book { BookID = 2, BookName = "combo banasonic", Description = "các thiết bị chụp hình ,nghe nhạc ", ImagePath ="hinh2.jpg", UnitPrice = 40.000f, CategoryID = 2 }, //book 3 new Book { BookID = 3, BookName = "double kĩ thuật số", Description = "bộ đôi điện thoại máy ảnh kĩ thuật số", ImagePath="images22.jpg", UnitPrice = 26.730f, CategoryID = 2 }, //book 4 new Book { BookID = 4, BookName = "double s6", Description = "điện thoại adroi và ios hàng 95%", ImagePath ="iphone-0.jpg", UnitPrice = 45.000f, CategoryID = 3 }, //book 5 new Book { BookID = 5, BookName = "Gấu bông qoobee agapi", Description = "Hàng tặng không bán", ImagePath="b64a4c1660433cb65501be2eade9caf8.jpg", UnitPrice = 0.0f, CategoryID = 4 }, }; return books; } } }<file_sep>/README.md # Shop Thiết bị Online WEB BÁN THIẾT BỊ ĐIỆN TỬ <img src="hinhanh/a.jpg"> _Nhấn vào giảm giá sẽ hiện ra các sản phẩm giảm giá <img src="hinhanh/aaa.jpg"> _Nhấn vào giảm giá sẽ hiện các sản phẩm giảm giá <img src="hinhanh/asd.jpg"> _NHấn vào hàng mẫu sẽ hiện các sản phẩm mẫu <img src="hinhanh/b.jpg"> _Nhấn vào hàng mới sã hiện các sản phẩm mới <img src="hinhanh/bb.jpg"> _Nhấn vào giỏ hàng để đặt đơn hàng <img src="https://raw.githubusercontent.com/nguyenhongnhatlam/BooksShopOnline/master/images/themvaogiohang.PNG"> Sua lai giao dien: <img src="hinhanh/Capture.png"> Cảm Ơn các bạn đã xem trang wed của mình!!
181845a608b6f45ad0d0874fdf9df6826a7d7ca2
[ "Markdown", "C#" ]
2
C#
nguyenhongnhatlam/BooksShopOnline
5894ceace8548b78d60d0b622f07264fe09f96a4
379917640ea815ae4a0951713fd295dc23556c70
refs/heads/master
<file_sep>import nltk from six import text_type def _get_kwarg(kwargs, key, default): if key in kwargs: arg = kwargs[key] del kwargs[key] else: arg = default return arg class CustomFreqDist(nltk.probability.FreqDist): def custom_plot(self, *args, **kwargs): try: from matplotlib import pylab except ImportError: raise ValueError( 'The plot function requires matplotlib to be installed.' 'See http://matplotlib.org/' ) if len(args) == 0: args = [len(self)] samples = [item for item, _ in self.most_common(*args)] cumulative = _get_kwarg(kwargs, 'cumulative', False) percents = _get_kwarg(kwargs, 'percents', False) if cumulative: freqs = list(self._cumulative_frequencies(samples)) ylabel = "Cumulative Counts" if percents: freqs = [f / freqs[len(freqs) - 1] * 100 for f in freqs] ylabel = "Cumulative Percents" else: freqs = [self[sample] for sample in samples] ylabel = "Counts" # percents = [f * 100 for f in freqs] only in ProbDist? pylab.grid(True, color="silver") if "linewidth" not in kwargs: kwargs["linewidth"] = 2 if "title" in kwargs: pylab.title(kwargs["title"]) del kwargs["title"] pylab.plot(freqs, **kwargs) pylab.xticks(range(len(samples)), [text_type(s) for s in samples], rotation=90) pylab.xlabel("Words") pylab.ylabel(ylabel) return pylab
ab957aad586c2195ff5a22a7ed7597fb4365da22
[ "Python" ]
1
Python
annabl38/Project_1
7c5eafc187200dc4363843fe0e76e384d428ab47
8a9102cd345bca531c0383ce5cfe9ed2f8beb60d
refs/heads/master
<file_sep>suite('Menu Link Tests', function() { test('page should contain links to HowTo, Team, Register & Blog page', function(){ assert($('a[href="wieesfunktioniert"]').length); assert($('a[href="team"]').length); assert($('a[href="http://www.guesswhapp.net/#/login"]').length); assert($('a[href="http://guesswhapp.blogspot.de/"]').length); }); });<file_sep>/*jslint node: true */ "use strict"; var express = require("express"), gwcode = require("./GuessWhappConfig.json"), //List of GuessWhapps which will be displayed Random on LandingPage app = express(); // set up handlebars view engine var handlebars = require("express3-handlebars") .create({ defaultLayout:"main"}); app.engine("handlebars", handlebars.engine); app.set("view engine", "handlebars"); app.set("port", process.env.PORT || 3000); app.use(express.static(__dirname + "/public")); // set "showTests" context property if the querystring contains test=1 app.use(function(req, res, next){ res.locals.showTests = app.get("env") !== "production" && req.query.test === "1"; next(); }); app.get("/", function(req, res) { var randomGWcode = gwcode[Math.floor(Math.random() * gwcode.length)]; res.render("home", { gwcode: randomGWcode, pageTestScript: "qa/tests-menuLinks.js" }); }); // routes app.get("/team", function(req,res){ res.render("team", {layout: "sub"}); }); app.get("/wieesfunktioniert", function(req,res){ res.render("wieesfunktioniert", {layout: "sub"}); }); app.get("/impressum", function(req,res){ res.render("impressum", {layout: "sub"}); }); // 404 catch-all handler (middleware) app.use(function(req, res, next){ res.status(404); res.render("404"); }); // 500 error handler (middleware) app.use(function(err, req, res, next){ console.error(err.stack); res.status(500); res.render("500"); }); app.listen(app.get("port"), function(){ console.log( "Express started on http://localhost:" + app.get("port") + "; press Ctrl-C to terminate." ); }); <file_sep># GuessWhapp DE Site ## built with node.js, Express and Handlebars.js This is the first public site created with the above stack
45df3227e5dd16912e7a1aa3ebfe6c81658a6adb
[ "JavaScript", "Markdown" ]
3
JavaScript
olafguesswhapp/GuessWhappNodeExpress
01c02d4a9dfa7cb562c82d3ffb3b942ab1cde151
286f693f91ec4814b74c613aa9ab30d6fe5016e9
refs/heads/master
<file_sep>import csv, json from flask import Flask,render_template app = Flask(__name__) @app.route("/") def index(): return render_template('index.html') @app.route('/maps/example1.json') def example1(): f = open('./static/js/maps/example1.json', 'rt', encoding='UTF8') print("stage1") data = f.read() print("stage2") return data @app.route('/maps/example2.json') def example2(): f = open('./static/js/maps/example2.json', 'rt', encoding='UTF8') print("stage1") data = f.read() print("stage2") return data if __name__ == '__main__': app.run(debug = True) <file_sep>import csv, json from flask import Flask,render_template,request app = Flask(__name__) @app.route("/") def home(): return render_template('main.html') @app.route("/index", methods = ['POST', 'GET']) def index(): data = request.form for key, value in data.items(): print(value) filename = str(value) return render_template('index.html', filename = filename) ''' data = request.form return render_template('result1.html', result1 = data) ''' @app.route('/maps/<string:filename>') def example(filename): file_path = './static/js/maps/' + filename f = open(file_path, 'rt', encoding='UTF8') print("stage1") data = f.read() print("stage2") return data if __name__ == '__main__': app.run(debug = True) <file_sep># snuMapHack Repository for SNU MapHack네 되네요 <file_sep>// jQuery.editable.js v1.1.2 // http://shokai.github.io/jQuery.editable // (c) 2012-2015 <NAME> <<EMAIL>> // The MIT License /* Liam */ var current = 0; var finish; (function($){ var escape_html = function(str){ return str.replace(/</gm, '&lt;').replace(/>/gm, '&gt;'); }; var unescape_html = function(str){ return str.replace(/&lt;/gm, '<').replace(/&gt;/gm, '>'); }; $.fn.editable = function(event, callback){ console.log("current is : " + current); console.log("this is : " + typeof event.target); console.log($(current).id); console.log($(this).id); console.dir(current); console.dir(this); current = this; if(typeof callback !== 'function') callback = function(){}; if(typeof event === 'string'){ var trigger = this; var action = event; var type = 'input'; } else if(typeof event === 'object'){ var trigger = event.trigger || this; if(typeof trigger === 'string') trigger = $(trigger); var action = event.action || 'click'; var type = event.type || 'input'; } else{ throw('Argument Error - jQuery.editable("click", function(){ ~~ })'); } var target = this; var edit = {}; edit.start = function(e){ console.log("Start"); trigger.unbind(action === 'clickhold' ? 'mousedown' : action); if(trigger !== target) trigger.hide(); var old_value = ( type === 'textarea' ? target.text().replace(/<br( \/)?>/gm, '\n').replace(/&gt;/gm, '>').replace(/&lt;/gm, '<') : target.text() ).replace(/^\s+/,'').replace(/\s+$/,''); var input = type === 'textarea' ? $('<textarea>') : $('<input>'); input.val(old_value). css('width', type === 'textarea' ? '100%' : target.width()+target.height() ). css('font-size','100%'). css('margin',0).attr('id','editable_'+(new Date()*1)). addClass('editable'); if(type === 'textarea') input.css('height', target.height()); console.log("finish is before : " + finish); finish = function(e){ var result = input.val().replace(/^\s+/,'').replace(/\s+$/,''); var html = escape_html(result); if(type === 'textarea') html = html.replace(/[\r\n]/gm, '<br />'); //tooltip도 html형식으로 해야 띄어지겠군. //아, br로 저장까진 좋은데,(finish후에 보이는게 띄어진 형태니까.) //그걸 다시 읽어오는 과정에서 저게 없어지네. 이럼 html로 해야하는가.? target.html(html); console.log("in finish, before callback()"); callback({value : result, target : target, old_value : old_value}); edit.register(); // for rebind if(trigger !== target) trigger.show(); }; console.log("finish is after : " + finish); input.blur(finish); // listener with handler $(window.document.body).on("click", function(event) { if(!($(event.target).hasClass("tooltipstered") || $(event.target).parents('.tooltipster-base').length > 0)) { input.blur(); } }); if(type === 'input'){ input.keydown(function(e){ // lisner with handler if(e.keyCode === 13) { // enter key finish()}; }); } target.html(input); input.focus(); // fire focus event. }; edit.register = function(){ if(action === 'clickhold'){ var tid = null; trigger.bind('mousedown', function(e){ tid = setTimeout(function(){ edit.start(e); }, 500); }); trigger.bind('mouseup mouseout', function(e){ clearTimeout(tid); }); } else{ console.log("rebind"); trigger.bind(action, edit.start); } }; edit.register(); return this; }; })(jQuery);
2126e31b0227cbf28845f80a2f64ed881e4ea24a
[ "Markdown", "Python", "JavaScript" ]
4
Python
Chipsama/snuMapHack
9d148b15893a3c585ade6669f7ac28c4ab3293f5
a5ab718c3a5a4d1e8cd70c61fa5597f9e633ecf8
refs/heads/master
<repo_name>alejandro945/coffee-shop<file_sep>/src/model/Ages.java package model; import java.util.ArrayList; public class Ages { private ArrayList<Double> ages; private double prom; public Ages() { this.ages = new ArrayList<Double>(); } public ArrayList<Double> getAges() { return ages; } public String addAges(double[] renderAges) { for (var age : renderAges) { ages.add(age); } return "The children ages have been added succesfully" + "\n"; } public String deleteAges() { ages.clear(); return "The Ages List have been deleted succesfully"; } public String showData() { String msg = ""; for (int i = 0; i < this.ages.size(); i++) { if (i != this.ages.size() - 1) { msg += ages.get(i) + " "; } else { msg += ages.get(i); } } return msg; } public void bubbleSort(ArrayList<Double> ages) { int cont = 0; for (int i = ages.size(); i > 0; i--) { for (int j = 0; j < i - 1; j++) { if (ages.get(j) > ages.get(j + 1)) { double temp = ages.get(j); ages.set(j, ages.get(j + 1)); ages.set(j + 1, temp); cont++; } } } double prom = ((ages.size() == 1) ? Math.floor((cont / ((double) (ages.size()))) * 100) / 100 : Math.floor((cont / ((double) (ages.size() - 1))) * 100) / 100); this.prom = prom; } public String showAgesSorted() { bubbleSort(ages); return prom + "-" + showData(); } }
c1915603d2f323a5c3ea4f6438af0c7ffb79669b
[ "Java" ]
1
Java
alejandro945/coffee-shop
1b9122d2f76af355f5a4c5064dfc5b16c3da630d
ab337515fa4b88a78111c5b82a8980d843de8f90
refs/heads/main
<file_sep>package swp490.spa.entities; import lombok.*; import javax.persistence.*; import java.io.Serializable; @Entity @NoArgsConstructor @AllArgsConstructor @Data @Getter @Setter @Table(name = "category", schema = "public") public class Category implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "name") private String name; @Column(name = "description") private String description; @ManyToOne @JoinColumn(name = "spa_id") private Spa spa; @Column(name = "status") private String status; } <file_sep>package swp490.spa.dto.responses; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.Column; @Data @NoArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) public class CategoryResponse { @JsonProperty("id") private Integer id; @JsonProperty("name") private String name; @JsonProperty("description") private String description; @JsonProperty("status") private String status; public CategoryResponse(Integer id, String name, String description, String status) { this.id = id; this.name = name; this.description = description; this.status = status; } } <file_sep>package swp490.spa.dto.helper; import org.springframework.data.domain.Page; import org.springframework.http.HttpStatus; import swp490.spa.dto.support.Response; import swp490.spa.dto.support.Paging; import swp490.spa.dto.support.Response; import java.util.List; public class ResponseHelper { public static <T> Response<T> ok(T data){ Response<T> response = new Response<>(); response.setCode(HttpStatus.OK.value()); response.setStatus(HttpStatus.OK.name()); response.setData(data); return response; } public static <T> Response<List<T>> ok(Page<T> page){ Response<List<T>> response = new Response<>(); response.setCode(HttpStatus.OK.value()); response.setStatus(HttpStatus.OK.name()); response.setData(page.getContent()); Paging paging = new Paging(); paging.setPage(page.getNumber()); paging.setItemPerPage(page.getSize()); paging.setTotalItem(page.getTotalElements()); paging.setTotalPage(page.getTotalPages()); response.setPaging(paging); return response; } } <file_sep>package swp490.spa.entities; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; import java.io.Serializable; @Entity @NoArgsConstructor @AllArgsConstructor @Getter @Setter @Table(name = "customer", schema = "public") public class Customer implements Serializable { @Id @Column(name = "user_id") private Integer id; @Column(name = "custom_type") private String customType; @OneToOne @MapsId @JoinColumn(name = "user_id") private User user; } <file_sep>package swp490.spa.services; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import swp490.spa.entities.SpaService; import swp490.spa.entities.Status; import swp490.spa.repositories.SpaServiceRepository; @Service public class SpaServiceService { private SpaServiceRepository spaServiceRepository; public SpaServiceService(SpaServiceRepository spaServiceRepository) { this.spaServiceRepository = spaServiceRepository; } public Page<SpaService> findBySpaIdAndStatus(Integer spaId, Status status, Pageable pageable){ return this.spaServiceRepository.findBySpaIdAndStatus(spaId, status, pageable); } } <file_sep>package swp490.spa.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import swp490.spa.entities.Customer; public interface CustomerRepository extends JpaRepository<Customer, Integer> { @Query("FROM Customer c where c.user.id = ?1") Customer findByUserId(Integer userId); } <file_sep>package swp490.spa.services; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import swp490.spa.entities.Category; import swp490.spa.repositories.CategoryRepository; import java.util.List; @Service public class CategoryService { private CategoryRepository categoryRepository; public CategoryService(CategoryRepository categoryRepository){ this.categoryRepository = categoryRepository; } public Page<Category> findAllByStatus(String status, Pageable pageable){ return this.categoryRepository.findByStatus(status, pageable); } // public List<Category> findAllByStatus(String status){ // return this.categoryRepository.findByStatus(status); // } } <file_sep>package swp490.spa.services; import org.springframework.stereotype.Service; import swp490.spa.entities.Customer; import swp490.spa.repositories.CustomerRepository; @Service public class CustomerService { private CustomerRepository customerRepository; public CustomerService(CustomerRepository customerRepository) { this.customerRepository = customerRepository; } public Customer findByUserId(Integer userId){ return customerRepository.findByUserId(userId); } } <file_sep>package swp490.spa.repositories; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import swp490.spa.entities.Spa; import swp490.spa.entities.Status; public interface SpaRepository extends JpaRepository<Spa, Integer> { Page<Spa> findByStatus(Status status, Pageable pageable); } <file_sep>package swp490.spa.mappers; import org.mapstruct.Mapper; import swp490.spa.dto.responses.CategoryResponse; import swp490.spa.entities.Category; @Mapper public interface CategoryMapper { CategoryResponse changeToCategoryResponse(Category category); } <file_sep>package swp490.spa.entities; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; import java.io.Serializable; @Entity @NoArgsConstructor @AllArgsConstructor @Getter @Setter @Table(name = "manager", schema = "public") public class Manager implements Serializable { @Id @Column(name = "user_id") private Integer id; @OneToOne @MapsId @JoinColumn(name = "user_id") private User user; @ManyToOne @JoinColumn(name = "spa_address_id") private SpaAddress spaAddress; } <file_sep>package swp490.spa.rest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import swp490.spa.dto.helper.ResponseHelper; import swp490.spa.dto.responses.StaffResponse; import swp490.spa.dto.support.Conversion; import swp490.spa.dto.support.Response; import swp490.spa.entities.Staff; import swp490.spa.services.StaffService; @RestController //@RequestMapping("/api/public") @RequestMapping("staff") @CrossOrigin public class StaffController { @Autowired private StaffService staffService; private Conversion conversion; public StaffController(StaffService staffService) { this.staffService = staffService; this.conversion = new Conversion(); } @GetMapping("/search/{userId}") public Response findStaffById(@PathVariable Integer userId){ Staff staff = staffService.findByStaffId(userId); return ResponseHelper.ok(staff); } } <file_sep>package swp490.spa.repositories; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import swp490.spa.entities.SpaAddress; public interface SpaAddressRepository extends JpaRepository<SpaAddress, Integer> { @Query("FROM SpaAddress s where s.spa.id = ?1") Page<SpaAddress> findBySpaId(Integer spaId, Pageable pageable); } <file_sep>package swp490.spa.rest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.web.bind.annotation.*; import swp490.spa.dto.responses.LoginResponse; import swp490.spa.dto.support.Conversion; import swp490.spa.dto.helper.ResponseHelper; import swp490.spa.dto.support.Response; import swp490.spa.entities.*; import swp490.spa.jwt.JWTUtils; import swp490.spa.services.*; import swp490.spa.services.SpaService; @RestController //@RequestMapping("/api/public") @RequestMapping("public") @CrossOrigin public class PublicController { @Autowired private UserService userService; @Autowired private CustomerService customerService; @Autowired private StaffService staffService; @Autowired private ManagerService managerService; @Autowired private CategoryService categoryService; @Autowired private SpaService spaService; @Autowired private SpaAddressService spaAddressService; @Autowired private SpaServiceService spaServiceService; @Autowired JWTUtils jwtUtils; private Conversion conversion; public PublicController(UserService userService, CategoryService categoryService, SpaService spaService, SpaAddressService spaAddressService, SpaServiceService spaServiceService, CustomerService customerService, StaffService staffService, ManagerService managerService) { this.userService = userService; this.categoryService = categoryService; this.spaService = spaService; this.spaAddressService = spaAddressService; this.spaServiceService = spaServiceService; this.customerService = customerService; this.staffService = staffService; this.managerService = managerService; this.conversion = new Conversion(); } @GetMapping("/category") public Response findCategoryByStatus(@RequestParam String status, Pageable pageable){ Page<Category> categories = categoryService.findAllByStatus(status, pageable); if (!categories.hasContent() && !categories.isFirst()) { categories = categoryService.findAllByStatus(status, PageRequest.of(categories.getTotalPages()-1, categories.getSize(), categories.getSort())); } return ResponseHelper.ok(conversion.convertToCategoryResponse(categories)); } @GetMapping("/user") public Response findUserByPhone(@RequestParam String phone){ User user = userService.findByPhone(phone); return ResponseHelper.ok(user); } @GetMapping("/spa") public Response findSpaByStatusAvailable(Pageable pageable){ Page<Spa> spas = spaService.findByStatus(Status.AVAILABLE,pageable); if(!spas.hasContent() && !spas.isFirst()){ spas = spaService.findByStatus(Status.AVAILABLE, PageRequest.of(spas.getTotalPages()-1, spas.getSize(), spas.getSort())); } return ResponseHelper.ok(conversion.convertToSpaResponse(spas)); } @GetMapping("/spaaddress") public Response findSpaAddressBySpaId(@RequestParam Integer spaId, Pageable pageable){ Page<SpaAddress> spaAddresses = spaAddressService.findBySpaId(spaId, pageable); if(!spaAddresses.hasContent() && !spaAddresses.isFirst()){ spaAddresses = spaAddressService.findBySpaId(spaId, PageRequest.of(spaAddresses.getTotalPages()-1, spaAddresses.getSize(), spaAddresses.getSort())); } return ResponseHelper.ok(conversion.convertToSpaAddressResponse(spaAddresses)); } @GetMapping("/spaservice") public Response findSpaServiceBySpaId(@RequestParam Integer spaId, @RequestParam Status status, Pageable pageable){ Page<swp490.spa.entities.SpaService> spaServices = spaServiceService.findBySpaIdAndStatus(spaId, status, pageable); if(!spaServices.hasContent() && !spaServices.isFirst()){ spaServices = spaServiceService.findBySpaIdAndStatus(spaId, status, PageRequest.of(spaServices.getTotalPages()-1, spaServices.getSize(), spaServices.getSort())); } return ResponseHelper.ok(conversion.convertToSpaServiceResponse(spaServices)); } @PostMapping("/login") public LoginResponse login (@RequestBody AuthRequest account){ User newAccount = userService.findByPhone(account.getPhone()); if(newAccount == null){ return LoginResponse.createErrorResponse(LoginResponse.Error.USERNAME_NOT_FOUND); } if(!newAccount.getPassword().equals(account.getPassword())){ return LoginResponse.createErrorResponse(LoginResponse.Error.WRONG_PASSWORD); } boolean isExisted = false; switch (account.getRole()){ case CUSTOMER: Customer customer = customerService.findByUserId(newAccount.getId()); if(customer!=null){ isExisted = true; } break; case MANAGER: Manager manager = managerService.findManagerById(newAccount.getId()); if(manager!=null){ isExisted = true; } break; case STAFF: Staff staff = staffService.findByStaffId(newAccount.getId()); if(staff!=null){ isExisted = true; } break; } if(isExisted == false){ return LoginResponse.createErrorResponse(LoginResponse.Error.ROLE_NOT_EXISTED); } String role = account.getRole().toString(); String token = jwtUtils.generateToken(newAccount.getPhone(), role); int userId = newAccount.getId(); return LoginResponse.createSuccessResponse(token,role,userId); } } <file_sep>package swp490.spa.entities; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; import java.io.Serializable; @Entity @NoArgsConstructor @AllArgsConstructor @Getter @Setter @Table(name = "spa_service", schema = "public") public class SpaService implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "name") private String name; @Column(name = "description") private String description; @Column(name = "price") private Double price; @Column(name = "duration_minute") private String duration; @Column(name = "service_next_hour") private Double serviceNext; @Column(name = "status") private Status status; @Column(name = "create_time") private String creatTime; @Column(name = "create_by") private String createBy; @ManyToOne @JoinColumn(name = "spa_id") private Spa spa; } <file_sep>package swp490.spa.mappers; import org.mapstruct.Mapper; import swp490.spa.dto.responses.SpaResponse; import swp490.spa.entities.Spa; @Mapper public interface SpaMapper { SpaResponse changeToSpaResponse(Spa spa); } <file_sep>package swp490.spa.dto.support; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import java.util.List; import java.util.Map; @Data @JsonInclude(JsonInclude.Include.NON_NULL) public class Response<T> { @JsonProperty("code") private Integer code; @JsonProperty("status") private String status; @JsonProperty("data") private T data; @JsonProperty("paging") private Paging paging; @JsonProperty("errors") private Map<String, List<String>> error; public Response() { } public Response(Integer code, String status, T data, Paging paging, Map<String, List<String>> error) { this.code = code; this.status = status; this.data = data; this.paging = paging; this.error = error; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public T getData() { return data; } public void setData(T data) { this.data = data; } public Paging getPaging() { return paging; } public void setPaging(Paging paging) { this.paging = paging; } public Map<String, List<String>> getError() { return error; } public void setError(Map<String, List<String>> error) { this.error = error; } } <file_sep>package swp490.spa.services; import org.springframework.stereotype.Service; import swp490.spa.entities.Manager; import swp490.spa.repositories.ManagerRepository; @Service public class ManagerService { private ManagerRepository managerRepository; public ManagerService(ManagerRepository managerRepository) { this.managerRepository = managerRepository; } public Manager findManagerById(Integer userId){ return this.managerRepository.findByUserId(userId); } } <file_sep>package swp490.spa.repositories; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import swp490.spa.entities.SpaService; import swp490.spa.entities.Status; public interface SpaServiceRepository extends JpaRepository<SpaService, Integer> { @Query("FROM SpaService s where s.spa.id = ?1 and s.status = ?2") Page<SpaService> findBySpaIdAndStatus(Integer spaId, Status status, Pageable pageable); }
e5b21d7a6656994266ca5fa419ca32d011ff8b8d
[ "Java" ]
19
Java
phongpttse63166/testLogin
0ecbedcb6d1c9ba9428ea3bda4de1bb11a7d4a3a
9248ee6e0c33b277dc23023c999ee64fb37541d6
refs/heads/master
<repo_name>yasha-o-d/Roll-My-Dice<file_sep>/main.cpp // main.cpp // Jesse's Actual Second Challenge // Created by <NAME> on 1/4/18. // Copyright © 2018 <NAME>. All rights reserved. #include <iostream> using namespace std; int main() { int nDice = 10; //Defines number of dice to be rolled int nSides = 6; //Defines number of side per dice int nSims = 1e8; //Defines number of simulations int Rolls[nDice]; //Initializes Array of rolls per simulation int reUse = nDice*nSides; //Used twice in code int SumCount[reUse]; //Initializes Array for the sum counter SumCount[reUse] = {0}; //Set all values to 0 int Sum = 0; //Initialize sum to 0 for (int sim = 0; sim < nSims; sim++){ //Increments through each simulation for (int i = 0; i < nDice; i++){ //Increments through dice per simulation Rolls[i] = (rand() % nSides)+1; //Generates random roll Sum+=Rolls[i]; //Adds up sum of all rolls for a given simulation } SumCount[Sum-1]++; //Counter for the sum of rolls for a given simulation Sum = 0; //Resets sum of all rolls for a given simulation } for (int k = 0; k < reUse; k++){ //Displays counter values cout << "A sum of " << k+1 << " was rolled " << SumCount[k] << " times." << endl; } return 0; } <file_sep>/README.md # Roll-My-Dice
6e0f6d4e9a8ac4ef407683ea035c04be78339d3b
[ "Markdown", "C++" ]
2
C++
yasha-o-d/Roll-My-Dice
b16ef7acf17834170278192a61b0d155931aecf7
71a477123988c595019d75ac71cb981b511c7b17
refs/heads/master
<repo_name>V1zz/Test.TextEditor<file_sep>/Test.TextEditor/StartForm.cs using System; using System.Drawing; using System.Windows.Forms; namespace Test.TextEditor { public interface IStartForm { string FilePath { get; } string Content { get; set; } void SetSymbolCount(int count); event EventHandler FileOpenClick; event EventHandler FileSaveClick; event EventHandler ContentChanged; } public partial class StartForm : Form, IStartForm { public StartForm() { InitializeComponent(); btnOpenFile.Click += new EventHandler(BtnOpenFile_Click); btnSaveFile.Click += BtnSaveFile_Click; tBoxContent.TextChanged += TBoxContent_TextChanged; btnSelectFile.Click += BtnSelectFile_Click; tBoxFontSize.ValueChanged += TBoxFontSize_ValueChanged; } #region IStartForm implementation public string FilePath => tBoxFilePath.Text; public string Content { get => tBoxContent.Text; set => tBoxContent.Text = value ?? throw new ArgumentNullException(paramName: value, message: "Attempt to set NULL value in the field \\'tBoxContent\\'"); } public void SetSymbolCount(int count) { sSLblSymbolsCountPrintOut.Text = count.ToString(); } public event EventHandler FileOpenClick; public event EventHandler FileSaveClick; public event EventHandler ContentChanged; #endregion #region EVENTS FORWARDING private void BtnOpenFile_Click(object sender, EventArgs e) { FileOpenClick?.Invoke(this, EventArgs.Empty); //if (FileOpenClick != null) FileOpenClick(this, EventArgs.Empty); ===> Original code } private void BtnSaveFile_Click(object sender, EventArgs e) { FileOpenClick?.Invoke(this, EventArgs.Empty); //if (FileOpenClick != null) FileOpenClick(this, EventArgs.Empty); ===> Original code } private void TBoxContent_TextChanged(object sender, EventArgs e) { FileOpenClick?.Invoke(this, EventArgs.Empty); //if (FileOpenClick != null) FileOpenClick(this, EventArgs.Empty); ===> Original code } #endregion #region Internal controls. ///<summary> /// Calls the standard file attachment dialog box, /// from the property of which the string value of the path to the file /// is assigned to the "FilePath" property after clicking "OK" button. /// The default display type is "* .tхt", but all types can be selected. /// When the user has selected the file, there is a need for confirmation by pressing the "OK" button. /// Calling the event again at the end of the function makes this easier by 2 clicks on the selected file. ///</summary> private void BtnSelectFile_Click(object sender, EventArgs e) { var dialog = new OpenFileDialog { Filter = "Text files|*.txt|All files|*.*" }; //Setting "FilePath" property to the string value of the path to the selected file, if "OK" is pressed. if (dialog.ShowDialog() == DialogResult.OK) { tBoxFilePath.Text = dialog.FileName; FileOpenClick?.Invoke(this, EventArgs.Empty); } } /// <summary> /// При установке размера шрифта значение Font Family будет заменено программным значением по умолчанию (). /// </summary> /// <defaults> /// <fontFamily> Calibri </fontFamily> /// </defaults> private void TBoxFontSize_ValueChanged(object sender, EventArgs e) { tBoxContent.Font = new Font("Calibri", (float)tBoxFontSize.Value); } #endregion private void tBoxContent_TextChanged_1(object sender, EventArgs e) { } } } <file_sep>/TextEditorCore/FileManager.cs using System.IO; using System.Text; namespace TextEditorCore { /// <summary> /// The "IFileManager" interface represents the implementation of the data access logic. /// </summary> public interface IFileManager { bool IsFileExists(string FilePath); int GetSymbCount(string content); string GetContent(string filePath); string GetContent(string filePath, Encoding encoding); void SaveContent(string content, string filePath); void SaveContent(string content, string filePath, Encoding encoding); } /// <summary> /// The FileManager class provides data to the client by implementing the IFileManager interface. /// Data provider: text document in ".txt" format. /// </summary> public class FileManager : IFileManager { private readonly Encoding _defaultEncoding = Encoding.GetEncoding(1251); public bool IsFileExists(string FilePath) { var isExists = File.Exists(FilePath); return isExists; } public int GetSymbCount(string content) { var count = content.Length; return count; } public string GetContent(string filePath) { return GetContent(filePath, _defaultEncoding); } public string GetContent(string filePath, Encoding encoding) { var content = File.ReadAllText(filePath, encoding); return content; } public void SaveContent(string content, string filePath) { SaveContent(content, filePath, _defaultEncoding); } public void SaveContent(string content, string filePath, Encoding encoding) { File.WriteAllText(filePath, content, encoding); } } } <file_sep>/Test.TextEditor/MessageService.cs using System.Windows.Forms; namespace Test.TextEditor { /// <summary> /// The "MessageService" class and its "IMessageService" interface are implemented /// with the aim of displaying (for example, by the Presenter) user messages from anywhere /// in the program to a request from the client side without having access to the code implementation itself. /// </summary> public interface IMessageService { void ShowMessage(string message); void ShowExclamination(string exclamination); void ShowWarning(string warning); void ShowError(string error); } public class MessageService : IMessageService { public void ShowMessage(string message) { MessageBox.Show( message , "Message:" , MessageBoxButtons.OK , MessageBoxIcon.Information ); } public void ShowExclamination(string exclamination) { MessageBox.Show( exclamination , "Exclamination:" , MessageBoxButtons.OK , MessageBoxIcon.Exclamation ); } public void ShowWarning(string warning) { MessageBox.Show( warning , "Warning:" , MessageBoxButtons.OK , MessageBoxIcon.Warning ); } public void ShowError(string error) { MessageBox.Show( error , "!!!ERROR!!!" , MessageBoxButtons.OK , MessageBoxIcon.Error ); } } } <file_sep>/Test.TextEditor/MainPresenter.cs using TextEditorCore; using System; namespace Test.TextEditor { public class MainPresenter { private readonly IStartForm _view; private readonly IFileManager _manager; private readonly IMessageService _messageService; public MainPresenter(IStartForm view, IFileManager manager, IMessageService messageService) { //Passing links to the implementation of the interfaces. _view = view; _manager = manager; _messageService = messageService; //Reseting the symbol counter _view.SetSymbolCount(0); //Implement event subscription _view.ContentChanged += new EventHandler(_view_ContentChanged); _view.FileOpenClick += new EventHandler(_view_FileOpenClick); _view.FileSaveClick += _view_FileSaveClick; } private void _view_FileSaveClick(object sender, EventArgs e) { throw new NotImplementedException(); } private void _view_FileOpenClick(object sender, System.EventArgs e) { try { string filePath = _view.FilePath; bool isExist = _manager.IsFileExists(filePath); // toDo: зачем? if (true) { } } catch (Exception e) { _messageService.ShowError(e.Message); } } private void _view_ContentChanged(object sender, System.EventArgs e) { var content = _view.Content; var count = _manager.GetSymbCount(content); _view.SetSymbolCount(count); } } }
79863e434aea06d89cd4efe31a41bb5f6e42045a
[ "C#" ]
4
C#
V1zz/Test.TextEditor
a2d53813e495cf32a83ce169f2d35234e45456ca
b273ee7c30e0aa47dfa1e1b3b563e15a13a6de0f
refs/heads/master
<repo_name>Kat-Kimani/Basics-of-String-Data<file_sep>/Basics of String Data/stringdata.cpp #include<iostream> #include<string> using namespace std; int main() { cout << "Capturing String Data Type and Limitation of cinn>> : \n"; string cinmyname; string getlinemyname; cout << " Type in your full name : "; getline (cin, getlinemyname); cout << " Type in your full name : "; cin >> cinmyname; //cin>> will output Catherine only // getline will output <NAME> cout << "\n"; cout << "Hey, Your name using cin>> is :" << cinmyname << endl; cout << "Hey, your Name using getline () function is :" << getlinemyname << endl; return 0; }
8af87cafc281e8da1dc4298e88433e9645a055fa
[ "C++" ]
1
C++
Kat-Kimani/Basics-of-String-Data
18cb32671caa3ff3c57527ec3654871f7bac1a49
e8dbc08c9206e4493fef59d6e7933b02c3057baf
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Text; namespace WhatsNewInCSharp8 { class DoingMany : IDoMany { public void Something() { throw new NotImplementedException(); } //public void Else() //{ // Console.WriteLine("DOne"); //} } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace WhatsNewInCSharp8 { public interface IDoMany { string What { get { return ""; } } string Azz { get { return ""; } } void Something(); //void Else() //{ Console.WriteLine(nameof(Else)); } //; void Deconstruct(out string what, out string azz) { what = What; azz = Azz; } } } <file_sep>using System; using System.Collections.Generic; using System.Drawing; using System.Text; using System.Windows.Forms; namespace WinFormsCoreLib.ControlsExtensions { public static partial class ControlExtension { public static Button Button(this Form that, EventHandler handler) { var control = that.New<Button>(); control.Click += handler; return control; } } } <file_sep>using System; using System.Device.Gpio; namespace IoT { class Program { static void Main(string[] args) { var driver = new System.Device.Gpio.Drivers.Windows10Driver(); var controller = new GpioController(PinNumberingScheme.Board, driver); controller.SetPinMode(1, PinMode.Output); controller.Write(1, PinValue.High); } } } <file_sep>using NonNullableLib; using System; using System.Linq; namespace EFGetStarted { class Program { static void Main() { using (var db = new OrdersContext()) { //Create Console.WriteLine("Inserting a new order"); db.Add(new Order { TrackingNumber = "123", ShippingAddress = new StreetAddress { City = "PORDENONE", Street = "VIA KENNEDY" } }); db.SaveChanges(); //var order = db.Orders.First(); } } } } <file_sep>using System.Drawing; using System.Windows.Forms; using WinFormsCoreLib.Extensions; namespace WinFormsCoreLib.ControlsExtensions { public static partial class ControlExtension { public static TControl Text<TControl>(this TControl that, string text) where TControl : Control { that.Text = text; return that; } public static TControl WithSuggestedName<TControl>(this TControl that, string name) where TControl: Control { if (name.IsNullOrWhiteSpace()) that.Name = $"{nameof(TControl)}{that.Controls.Count:00}"; else that.Name = name; return that; } public static TControl Size<TControl>(this TControl that, int wh) where TControl : Control { return that.Size(wh, wh); } public static TControl Size<TControl>(this TControl that, int width, int height) where TControl : Control { that.Size = new Size( width > 0 ? width : that.Parent.ClientSize.Width-that.Location.X+width, height > 0 ? height : that.Parent.ClientSize.Height - that.Location.Y + height ); return that; } public static TControl Location<TControl>(this TControl that, int x, int y) where TControl : Control { that.Location = new Point( x > 0 ? x : that.Parent.ClientSize.Width + x, y > 0 ? y : that.Parent.ClientSize.Height + y ); return that; } public static TControl Location<TControl>(this TControl that, int xy) where TControl : Control { return that.Location(xy, xy); } public static TControl Anchor<TControl>(this TControl that, AnchorStyles styles) where TControl : Control { that.Anchor = styles; return that; } public static TControl AnchorLT<TControl>(this TControl that) where TControl : Control { return that.Anchor(AnchorStyles.Left | AnchorStyles.Top); } public static TControl AnchorRB<TControl>(this TControl that) where TControl : Control { return that.Anchor(AnchorStyles.Right | AnchorStyles.Bottom); } public static TControl AnchorAll<TControl>(this TControl that) where TControl : Control { return that.Anchor(AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom); } public static TControl Background<TControl>(this TControl that, Color? color = null) where TControl : Control { that.BackColor = color ?? Color.White; return that; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; namespace WinFormsCoreLib.ControlsExtensions { public static partial class TextBoxExtension { } } <file_sep>using Newtonsoft.Json; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using WinFormsCoreLib.Controls; using WinFormsCoreLib.ControlsExtensions; using WinFormsCoreLib.Forms; namespace WinFormIoTHubGateway { public static partial class WaveEditor { public static Form CreateNew() { var form = FormBase.New(); var drawingBox = form .New<DrawingBox>(); drawingBox .Location(16) .Size(-16, -60) .OnMouseMove((s, e) => { }) .AnchorAll() ; form.OnKeyDown((s, e) => { if (e.KeyCode == Keys.C && e.Control) { Copy(drawingBox); } else if (e.KeyCode == Keys.X && e.Control) { Copy(drawingBox); Clear(drawingBox); } else if (e.KeyCode == Keys.V && e.Control) { Paste(drawingBox, e.Alt); } }) ; form.KeyPreview = true; return form; } private static void Clear(DrawingBox drawingBox) { drawingBox.Bitmap.Clear(); } private static void Copy(DrawingBox drawingBox) { List<float?> scans = CopyImpl(drawingBox); var text = JsonConvert.SerializeObject(scans); Clipboard.SetText(text, TextDataFormat.Text); } private static List<float?> CopyImpl(DrawingBox drawingBox) { var bitmap = drawingBox.Bitmap; var scans = new List<float?>(); for (var x = 0; x < bitmap.Current.Width; x++) { var cs = new List<float>(); for (var y = bitmap.Current.Height - 1; y >= 0; y--) { var color = bitmap.Current.GetPixel(x, y); if (bitmap.IsTransparent(color)) continue; // if transparent...no way var yy = (float)(bitmap.Current.Height - y) / (float)bitmap.Current.Height; cs.Add(yy); } if (cs.Any()) scans.Add(cs.Average()); else scans.Add(null); } return scans; } private static void Paste(DrawingBox drawingBox, bool withClear = false) { if (!Clipboard.ContainsText(TextDataFormat.Text)) return; var jsonTentative = Clipboard.GetText(TextDataFormat.Text); try { var scans = JsonConvert.DeserializeObject<float?[]>(jsonTentative); if (withClear) Clear(drawingBox); PasteImpl(drawingBox, scans); } catch { // nothing to do } } private static void PasteImpl(DrawingBox drawingBox, float?[] scans) { var bitmap = drawingBox.Bitmap; bitmap.Clear(); var dx = (float)scans.Length / (float)bitmap.Current.Width; var sx = 0.0f; bool lastWasNull = true; for (var x = 0; x < bitmap.Current.Width; x++) { var scan = scans[(int)sx]; if (scan == null) { sx += dx; lastWasNull = true; continue; } var y = (int)((1.0f - scan) * (float)bitmap.Current.Height); bitmap.Current.SetPixel(x, y, System.Drawing.Color.Red); if (lastWasNull) { bitmap.MoveTo(x, y); lastWasNull = false; } else { bitmap.DrawTo(x, y); } } drawingBox.Invalidate(); } } } <file_sep>using System.Windows.Forms; namespace WinFormsCoreLib.ControlsExtensions { public static partial class ControlExtension { public static TControl OnKeyPress<TControl>(this TControl that, KeyPressEventHandler handler) where TControl: Control { that.KeyPress += handler; return that; } public static TControl OnKeyDown<TControl>(this TControl that, KeyEventHandler handler) where TControl : Control { that.KeyDown += handler; return that; } } } <file_sep>using Microsoft.Azure.Cosmos; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json.Linq; using NonNullableLib; using System; using System.Linq; using System.Threading.Tasks; namespace Cosmos { public class Program { static async Task Main() { using (var context = new OrderContext()) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); var order = new Order { Id = 1, TrackingNumber = "123", ShippingAddress = new StreetAddress { City = "London", Street = "221 B Baker St" } }; context.Add(order); await context.SaveChangesAsync(); } using (var context = new OrderContext()) { await foreach (var item in context.Orders) { Console.WriteLine($"{item.TrackingNumber}"); } } using (var context = new OrderContext()) { var cosmosClient = context.Database.GetCosmosClient(); var database = cosmosClient.GetDatabase("Points"); var container = database.GetContainer("Orders"); var resultSet = container.GetItemQueryIterator<JObject>(new QueryDefinition("select * from o")); var order = (await resultSet.ReadNextAsync()).First(); Console.WriteLine($"First order JSON: {order}"); order.Remove("TrackingNumber"); await container.ReplaceItemAsync(order, order["id"].ToString()); } } } } <file_sep>using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using WinFormsCoreLib.Controls; using WinFormsCoreLib.Forms; using WinFormsCoreLib.ControlsExtensions; namespace WinFormIoTHubGateway { public static partial class Program { [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var form = FormBase.New(); form.IsMdiContainer = true; form.WindowState = FormWindowState.Maximized; form.Text = "IoTHub Gateway"; form.Menu = new MainMenu(new[] { new MenuItem("&File", new[]{ new MenuItem("&WaveEditor", (s,e)=>{ var c = WaveEditor.CreateNew(); c.MdiParent = form; c.Show(); }), new MenuItem("-"), new MenuItem("E&xit", (s,e)=>{ Application.Exit(); }) }) }); Application.Run(form); } } }<file_sep>using System.Windows.Forms; namespace WinFormsCoreLib.ControlsExtensions { public static partial class ControlExtension { public static TControl OnMouseMove<TControl>(this TControl that, MouseEventHandler handler) where TControl: Control { that.MouseMove += handler; return that; } } } <file_sep>namespace NonNullableLib { #region Order public class Order { public int Id { get; set; } public string TrackingNumber { get; set; } //public string PartitionKey { get; set; } public StreetAddress ShippingAddress { get; set; } } #endregion } <file_sep>using NonNullableLib; using System; using System.Text.Json; using System.Threading.Tasks; namespace DotNetCore3 { class Program { static async Task Main(string[] args) { Console.WriteLine("Hello World!"); //Json(); //SQLClient(); Console.ReadLine(); } static void Json() { Order order = default; string json = default; order = new Order { Id = 1, TrackingNumber = "123", ShippingAddress = new StreetAddress { City = "London", Street = "221 B Baker St" } }; json = JsonSerializer.Serialize(order); //json = System.IO.File.ReadAllText("order.json"); //order = JsonSerializer.Deserialize<Order>(json); } static async Task SQLClient() { var client = new Microsoft.Data.SqlClient.SqlConnection(""); await client.OpenAsync(); var cmd = client.CreateCommand(); cmd.CommandText = "SELECT Id, TrackingNumber FROM dbo.Orders"; var result = await cmd.ExecuteReaderAsync(); while (await result.ReadAsync()) { var value = result.GetString(1); } await client.CloseAsync(); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace WinFormsCoreLib.Extensions { static partial class StringExtension { public static bool IsNullOrWhiteSpace(this string that) => string.IsNullOrWhiteSpace(that); } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using static System.Console; namespace WhatsNewInCSharp8 { class Program { static async Task Main(string[] args) { // 1. Default Interface Implementation // 2. Pattern Matching PatternMatching(); // 3. Using Declarations UsingDeclarations(); // 4. Static Local Function StaticLocalFunction(); // 5. Indices and Ranges IndicesAndRanges(); // 6. Null Coalescing Assignment NullCoalescingAssignment(); // 7. StackAlloc in nested expression StackAllocInNestedExpressions(); //////////////////// // 8. Non Nullable Reference Types // 9. Async Streams await AsyncStreams(); } private static void StackAllocInNestedExpressions() { Span<int> numbers = stackalloc[] { 1, 2, 3, 4, 5, 6 }; var ind = numbers.IndexOfAny(stackalloc[] { 2, 4, 6, 8 }); Console.WriteLine(ind); // output: 1 } private static void NullCoalescingAssignment() { List<int> numbers = null; int? a = null; // syntax now useful also in assignment not in expression (numbers ??= new List<int>()).Add(5); numbers.Add(a ??= 0); } private static void IndicesAndRanges() { var words = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; WriteLine($"Last one: {words[^1]}"); var range = 1..4; // System.Index var range1_4 = words[range]; // System.Range var range__2__0 = words[^2..^0]; var allWords = words[..]; var firstPhrase = words[..4]; var lastPhrase = words[6..]; } private static void StaticLocalFunction() { int y = 5; int x = 7; _ = Add(x, y); static int Add(int left, int right) => left + right; } private static void UsingDeclarations() { // implicit block definition using var reader = new StreamReader("File.txt"); } static void PatternMatching() { // switch expression var x = 1; var y = x switch { 1 => 10, // case: 2 => 20, _ => 30 // discard }; // property patterns IDoMany s = default; var f = s switch { { What: "WW" } => "ew", { Azz: "EE" } => "ff", _ => "oo" }; // positional pattern var ff = s switch { var (w, a) when w == "WW" && a == "" => "", var (w, a) when a == "AA" && w == "" => "", var (_,a) when a == "BB" => "", _ => "" }; // tuple patterns var aa = ""; var bb = ""; var xd = (aa, bb) switch { ("", "") => "Hello", (_, _) => "OI" }; } public static async System.Collections.Generic.IAsyncEnumerable<int> GenerateSequence() { for (int i = 0; i < 20; i++) { await Task.Delay(100); yield return i; } } private static async Task AsyncStreams() { await foreach (var number in GenerateSequence()) { Console.WriteLine(number); } } } } <file_sep>using Microsoft.EntityFrameworkCore; using NonNullableLib; namespace Cosmos { public class OrderContext : DbContext { public DbSet<Order> Orders { get; set; } #region Configuration protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseCosmos( "https://<host>.documents.azure.com:443/", "", databaseName: "Points"); #endregion protected override void OnModelCreating(ModelBuilder modelBuilder) { #region DefaultContainer modelBuilder.HasDefaultContainer("Orders"); #endregion #region Container modelBuilder.Entity<Order>() .ToContainer("Orders"); #endregion #region PartitionKey //modelBuilder.Entity<Order>() // .HasPartitionKey(o => o.PartitionKey); #endregion #region PropertyNames modelBuilder.Entity<Order>().OwnsOne( o => o.ShippingAddress, sa => { sa.ToJsonProperty("Address"); sa.Property(p => p.Street).ToJsonProperty("ShipsToStreet"); sa.Property(p => p.City).ToJsonProperty("ShipsToCity"); }); #endregion } } } <file_sep>using System; using System.Windows.Forms; namespace WinFormsCoreLib.ControlsExtensions { public static partial class FormExtension { public static TControl New<TControl>(this Form that, string name = null) where TControl: Control { var control = Activator.CreateInstance<TControl>(); control.WithSuggestedName(name); control.AnchorLT(); that.Controls.Add(control); return control; } } } <file_sep>using System.Collections.Generic; using Microsoft.EntityFrameworkCore; using NonNullableLib; namespace EFGetStarted { public class OrdersContext : DbContext { public DbSet<Order> Orders { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder options) => options.UseSqlServer(""); protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Order>(b => { b.Property<int>(nameof(Order.Id)) .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<string>(nameof(Order.TrackingNumber)) .HasColumnType("nvarchar(32)"); b.HasKey(nameof(Order.Id)); b.OwnsOne(nameof(Order.ShippingAddress), nameof(Order.ShippingAddress), bb => { bb.Property<string>(nameof(StreetAddress.City)) .HasColumnType("nvarchar(32)").HasColumnName("City"); bb.Property<string>(nameof(StreetAddress.Street)) .HasColumnType("nvarchar(32)").HasColumnName("Street"); }); b.ToTable("Orders"); }); modelBuilder.Entity<Order>().OwnsOne(p => p.ShippingAddress); } } } <file_sep>using System; using System.Drawing; using System.Windows.Forms; using WinFormsCoreLib.Tools; using WinFormsCoreLib.ControlsExtensions; namespace WinFormsCoreLib.Controls { public class DrawingBox: Control { public DrawingBitmap Bitmap { get; private set; } = new DrawingBitmap(); private float dx, dy; public Point Map(Point set) => new Point((int)(set.X / dx), (int)(set.Y / dy)); public DrawingBox() { Bitmap.Buffer(24 * 60, 1000); } protected override void OnResize(EventArgs e) { base.OnResize(e); dx = (float)this.DisplayRectangle.Width / (float)Bitmap.Size.Width; dy = (float)this.DisplayRectangle.Height / (float)Bitmap.Size.Height; Repaint(); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); Repaint(); } private void Repaint() { using (var myBuffer = BufferedGraphicsManager.Current.Allocate(this.CreateGraphics(), this.DisplayRectangle)) { myBuffer.Graphics.DrawImage(Bitmap.Current, this.DisplayRectangle); myBuffer.Render(); } } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (e.IsLeftButtonDown()) { Bitmap.DrawTo(Map(e.Location)); Repaint(); } else { Bitmap.MoveTo(Map(e.Location)); } } } } <file_sep>using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; namespace WinFormsCoreLib.ControlsExtensions { public static class MouseEventArgsExtension { public static bool IsLeftButtonDown(this MouseEventArgs that) => (that.Button & MouseButtons.Left) == MouseButtons.Left; public static bool IsLeftButtonUp(this MouseEventArgs that) => (that.Button & MouseButtons.Left) != MouseButtons.Left; public static bool IsRightButtonDown(this MouseEventArgs that) => (that.Button & MouseButtons.Right) == MouseButtons.Right; public static bool IsRightButtonUp(this MouseEventArgs that) => (that.Button & MouseButtons.Right) != MouseButtons.Right; } } <file_sep>using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Text; namespace WinFormsCoreLib.Tools { public class DrawingBitmap { private Color transparent; private Bitmap buffer; private Graphics graphics; private Point p1; public Bitmap Current => buffer; public Graphics Graphics => graphics; public bool IsTransparent(Color color) => color.ToArgb() == transparent.ToArgb(); public DrawingBitmap() { this.transparent = Color.White; } public DrawingBitmap Buffer(int x, int y, Color? transparent = null) { // backed image buffer = new Bitmap(x, y, PixelFormat.Format32bppArgb); graphics = Graphics.FromImage(buffer); Clear(transparent); return this; } public void Clear(Color? transparent = null) { if (transparent != null) this.transparent = transparent.Value; graphics.Clear(this.transparent); } public DrawingBitmap MoveTo(Point p) { p1 = p; return this; } public DrawingBitmap MoveTo(int x, int y) => MoveTo(new Point(x, y)); public DrawingBitmap DrawTo(Point p, Pen? pen = null) { graphics.DrawLine(pen ?? Pens.Black, p1, p); p1 = p; return this; } public DrawingBitmap DrawTo(int x, int y, Pen? pen = null) => DrawTo(new Point(x, y), pen); public Size Size => Current.Size; } } <file_sep>namespace NonNullableLib { #region StreetAddress public class StreetAddress { public string Street { get; set; } public string City { get; set; } } #endregion }
607db889a868e5d97afba63eb411879ae5dbc9ea
[ "C#" ]
23
C#
marcoparenzan/NetConf2019
413f228aac2627b489fdd6c92af52d8602a07f93
cd8201901ee30c12589b4f932986c740e679e5a4
refs/heads/master
<repo_name>nkn1/gtestLearnning<file_sep>/main.cpp #include "gtest/gtest.h" TEST(targetFunction01, 00001) { EXPECT_EQ(1, 1); } TEST(targetFunction01, 00002) { EXPECT_EQ(1, 1); } TEST(targetFunction01, 00003) { EXPECT_EQ(1, 1); } TEST(targetFunction01, 00004) { EXPECT_EQ(1, 1); } TEST(targetFunction01, 00005) { EXPECT_EQ(1, 1); } TEST(targetFunction01, 00006) { EXPECT_EQ(1, 1); } TEST(targetFunction01, 00007) { EXPECT_EQ(1, 1); } TEST(targetFunction01, 00008) { EXPECT_EQ(1, 1); } TEST(targetFunction01, 00009) { EXPECT_EQ(1, 1); } TEST(targetFunction01, 00010) { EXPECT_EQ(1, 1); } TEST(targetFunction01, 00011) { EXPECT_EQ(1, 1); } TEST(targetFunction01, 00012) { EXPECT_EQ(1, 1); } TEST(targetFunction01, 00013) { EXPECT_EQ(1, 1); } TEST(targetFunction01, 00014) { EXPECT_EQ(1, 1); } TEST(targetFunction01, 00015) { EXPECT_EQ(1, 1); } TEST(targetFunction01, 00016) { EXPECT_EQ(1, 1); } TEST(targetFunction01, 00017) { EXPECT_EQ(1, 1); } TEST(targetFunction02, 00001) { EXPECT_EQ(1, 1); } TEST(targetFunction02, 00002) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00001) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00002) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00003) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00004) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00005) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00006) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00007) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00008) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00009) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00010) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00011) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00012) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00013) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00014) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00015) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00016) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00017) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00018) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00019) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00020) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00021) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00022) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00023) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00024) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00025) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00026) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00027) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00028) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00029) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00030) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00031) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00032) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00033) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00034) { EXPECT_EQ(1, 1); } TEST(targetFunction03, 00035) { EXPECT_EQ(1, 1); } TEST(targetFunction04, 00001) { EXPECT_EQ(1, 1); } TEST(targetFunction04, 00002) { EXPECT_EQ(1, 1); } TEST(targetFunction04, 00003) { EXPECT_EQ(1, 1); } TEST(targetFunction04, 00004) { EXPECT_EQ(1, 1); } TEST(targetFunction04, 00005) { EXPECT_EQ(1, 1); } TEST(targetFunction04, 00006) { EXPECT_EQ(1, 1); } TEST(targetFunction04, 00007) { EXPECT_EQ(1, 1); } TEST(targetFunction04, 00008) { EXPECT_EQ(1, 1); } TEST(targetFunction04, 00009) { EXPECT_EQ(1, 1); } TEST(targetFunction04, 00010) { EXPECT_EQ(1, 1); } TEST(targetFunction04, 00011) { EXPECT_EQ(1, 1); } TEST(targetFunction04, 00012) { EXPECT_EQ(1, 1); } TEST(targetFunction04, 00013) { EXPECT_EQ(1, 1); } TEST(targetFunction04, 00014) { EXPECT_EQ(1, 1); } TEST(targetFunction04, 00015) { EXPECT_EQ(1, 1); } TEST(targetFunction04, 00016) { EXPECT_EQ(1, 1); } TEST(targetFunction04, 00017) { EXPECT_EQ(1, 1); } TEST(targetFunction04, 00018) { EXPECT_EQ(1, 1); } TEST(targetFunction04, 00019) { EXPECT_EQ(1, 1); } TEST(targetFunction04, 00020) { EXPECT_EQ(1, 1); } TEST(targetFunction04, 00021) { EXPECT_EQ(1, 1); } TEST(targetFunction04, 00022) { EXPECT_EQ(1, 1); } TEST(targetFunction04, 00023) { EXPECT_EQ(1, 1); } TEST(targetFunction05, 00001) { EXPECT_EQ(1, 1); } TEST(targetFunction05, 00002) { EXPECT_EQ(1, 1); } TEST(targetFunction05, 00003) { EXPECT_EQ(1, 1); } TEST(targetFunction05, 00004) { EXPECT_EQ(1, 1); } TEST(targetFunction05, 00005) { EXPECT_EQ(1, 1); } TEST(targetFunction05, 00006) { EXPECT_EQ(1, 1); } <file_sep>/Makefile all: g++ -c -I/usr/local/include main.cpp g++ main.o /usr/local/lib/gtest_main.a -lpthread clean: @rm -fr *.o a.out
e8c5b11b41fe3d6dd4f9de7a39178c283584eadd
[ "Makefile", "C++" ]
2
C++
nkn1/gtestLearnning
b61d6ba79cdc0b77945618f05919e02735d55920
718242e545ef13d1874bf2e7e7d5c98ae7aca45e
refs/heads/master
<repo_name>edlerd/imagelib<file_sep>/src/02-python.sh #!/bin/bash # load virtualenvwrapper for python (after custom PATHs) venvwrap="virtualenvwrapper.sh" /usr/bin/which $venvwrap if [ $? -eq 0 ]; then venvwrap=`/usr/bin/which $venvwrap` source $venvwrap fi workon OpenCV-3.4.3-py3 cd /root/src ipython -i imageload.py <file_sep>/01-docker.sh #!/bin/bash # load image from web #docker pull spmallick/opencv-docker:opencv # allow opening graphics on host machine xhost +local:docker # start ipython in container docker run --volume ~/dev/cv/src:/root/src --device=/dev/video0:/dev/video0 -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY=$DISPLAY -p 5000:5000 -p 8888:8888 -it spmallick/opencv-docker:opencv /root/src/02-python.sh <file_sep>/src/imageload.py import cv2 import numpy as np img = cv2.imread('grass.jpg') def relight(img, diff): height, width, channels = img.shape for y in range(0, width): for x in range(0, height): for c in range(0, channels): img[x,y,c] = max(0, min(255, (img[x,y,c] + diff))) def hist(img): height, width, channels = img.shape hist = np.zeros(256, np.uint32) for y in range(0, width): for x in range(0, height): hist[img[x,y]] += 1 print(' '.join(str(e) for e in hist)) def histNorm(img): height, width, channels = img.shape hist = np.zeros(256, np.uint32) N = 0 for y in range(0, width): for x in range(0, height): hist[img[x,y]] += 1 N += 1 histNorm = np.zeros(256, np.float64) for i in range(0, 256): histNorm[i] = hist[i] / N print(' '.join(str(e) for e in histNorm)) def histConvol(img): height, width, channels = img.shape hist = np.zeros(256, np.uint32) N = 0 for y in range(0, width): for x in range(0, height): hist[img[x,y,0]] += 1 N += 1 histConvol = np.zeros(256, np.float64) for i in range(0, 256): histConvol[i] = hist[i] / N for i in range(1, 256): histConvol[i] += histConvol[i-1] print(' '.join(str(e) for e in histConvol)) def show(img): cv2.imshow('image',img) cv2.waitKey(0) cv2.destroyAllWindows() def monochrome(img): height, width, channels = img.shape for y in range(0, width): for x in range(0, height): img[x,y] = 0.28*img[x,y,0] + 0.59*img[x,y,1] +0.13*img[x,y,2] def foo(): height, width, channels = img.shape r = np.zeros((height, width, 3), np.uint8) g = np.zeros((height, width, 3), np.uint8) b = np.zeros((height, width, 3), np.uint8) grey = np.zeros((height, width, 3), np.uint8) # kanäle aufsplitten for y in range(0, width): for x in range(0, height): r[x,y] = img[x,y,0] g[x,y] = img[x,y,1] b[x,y] = img[x,y,2] grey[x,y] = 0.25*img[x,y,0] + 0.5*img[x,y,1] +0.25*img[x,y,2] cv2.imwrite('r.jpg', r) cv2.imwrite('g.jpg', g) cv2.imwrite('b.jpg', b) cv2.imwrite('grey.jpg', grey) # cutoff image other = np.zeros((height, width, 1), np.uint8) for y in range(0, width): for x in range(0, height): other[x,y] = min(max(0.25*img[x,y,0] + 0.5*img[x,y,1] +0.25*img[x,y,2], 50), 200) cv2.imwrite('other.jpg', other) <file_sep>/README.md Startup scripts for opencv docker image and load some helper functions for handling images.
fe1dcf21f614178d15345d5e1cc62239afc07707
[ "Markdown", "Python", "Shell" ]
4
Shell
edlerd/imagelib
3b076217b90876ab43a68ea08e287834be6c5bcb
133f6b6dbee61df1e15bff42959baa3a98002d00
refs/heads/master
<file_sep>/** * @copyright 2017 <NAME>, <EMAIL> */ #ifndef _MTLOBJECTEXCEPTIONS_HPP_ #define _MTLOBJECTEXCEPTIONS_HPP_ #include <exception> using namespace std; class MtlParseException : public exception { const char * what () const throw () { return "Failed parsing the file"; } }; #endif /* _MTLOBJECTEXCEPTIONS_HPP_ */ <file_sep>/** * @copyright 2017 <NAME>, <EMAIL> */ #ifndef MTLOBJECT_HPP #define MTLOBJECT_HPP #include <string> #include <vector> #include "MtlMap.hpp" #include "MtlMaterial.hpp" class MtlObject { public: MtlObject(const std::string& fileName); ~MtlObject(void); void printMaterials(void); std::string mFileName; std::vector<MtlMaterial *> materials; private: void skipOptionalChars(const std::string& data, std::string::size_type& pos); void skipToNextLine(const std::string& data, std::string::size_type& pos); }; #endif /* MTLOBJECT_HPP */ <file_sep>/** * @copyright 2017 <NAME>, <EMAIL> */ #include <fstream> #include <iostream> #include <list> #include <sstream> #include <stdexcept> #include <string> #include <tuple> #include "MtlObject.hpp" #include "MtlObject_int.hpp" #include "MtlObjectExceptions.hpp" #define MATERIAL_SENINTEL "newmtl" #define MATERIAL_SENINTEL_LEN 7 using namespace std; static void parseLine(vector<MtlMaterial *>& materials, const string& data); MtlObject::MtlObject(const string& fileName) : mFileName(fileName) { ifstream dataFile(fileName); string line; if (!dataFile.is_open()) { cerr << "Failed to open file '" << fileName << "'" << endl; } while (getline(dataFile, line)) { parseLine(materials, line); } dataFile.close(); } MtlObject::~MtlObject(void) { materials.clear(); } void MtlObject::printMaterials(void) { cout << "Object '" << mFileName << "'" << endl; for (unsigned int i = 0; i < materials.size(); ++i) { if (materials[i]) { materials[i]->printProperties(" ", ((i + 1) == materials.size())); } } } static void skipOptionalChars(const string& data, string::size_type& pos) { while ((data[pos] == '\'') || (data[pos] == ' ') || (data[pos] == '"')) ++pos; } static void parseParam3Floats(const string& data, string::size_type& pos, float value[]) { /* Extract first float */ skipOptionalChars(data, pos); string::size_type endPos = data.find(" ", pos); value[0] = stof(data.substr(pos, (endPos != string::npos ? endPos - pos : endPos))); pos = endPos; /* Extract second float */ skipOptionalChars(data, pos); endPos = data.find(" ", pos); value[1] = stof(data.substr(pos, (endPos != string::npos ? endPos - pos : endPos))); pos = endPos; /* Extract third float */ skipOptionalChars(data, pos); endPos = data.find(" ", pos); value[2] = stof(data.substr(pos, (endPos != string::npos ? endPos - pos : endPos))); pos = endPos; } static void parseParamFloat(const string& data, string::size_type& pos, float& value) { skipOptionalChars(data, pos); string::size_type left = 0; value = stof(data.substr(pos), &left); pos += left; } static void parseParamInt(const string& data, string::size_type& pos, int& value) { skipOptionalChars(data, pos); string::size_type left = 0; value = stoi(data.substr(pos), &left); pos += left; } static void parseParamString(const string& data, string::size_type& pos, string& value) { skipOptionalChars(data, pos); string::size_type endPos = data.find(" ", pos); value = data.substr(pos, (endPos != string::npos ? endPos - pos : endPos)); pos = endPos; } static void parseOptions(const string& data, string::size_type& pos, size_t nrOptions, const mtlOpt* options, vector<tuple<const mtlOpt&, void *>>& values) { for (size_t i = 0; i < nrOptions; ++i) { const string& option = options[i].optName; const mtlOptType type = options[i].optType; const string::size_type length = string(const_cast<const char *>( options[i].optName)).length(); string::size_type localPos = 0; if (data.compare(pos, length, option) || (data[pos + 1] != ' ')) continue; localPos = pos + length; tuple<const mtlOpt&, void *> value(options[i], nullptr); switch (type) { case VT_EMPTY: /* tuple value is already nullptr */ break; case VT_3FLOATS: { float* fVals = new float[3]{0}; parseParam3Floats(data, localPos, fVals); get<1>(value) = static_cast<void *>(fVals); } break; case VT_FLOAT: { float* fVal = new float(0); parseParamFloat(data, localPos, *fVal); get<1>(value) = static_cast<void *>(fVal); } break; case VT_INT: { int* iVal = new int(0); parseParamInt(data, localPos, *iVal); get<1>(value) = static_cast<void *>(iVal); } break; default: cerr << "Error parsing options" << endl; throw MtlParseException(); } cout << "Adding tuple ("<< get<0>(value).optName << ", " << get<1>(value) << ")" << endl; values.push_back(value); } } static void parseLine(vector<MtlMaterial *>& materials, const string& data) { /* MtlColor ambientColor, diffuseColor, specularColor; // Ka, Kd, Ks (3 * [0 - 255]) int illumination; // illum float dissolve; // d (0.0 - 1.0) float specularExponent; // Ns (0 - 1000) float sharpness; // sharpness float opticalDensity; // Ni (0.001 - 10.0) MtlMap mapAmbientColor; // map_Ka (options filename) MtlMap mapDiffuseColor; // map_Kd (options filename) MtlMap mapSpecularColor; // map_Ks (options filename) MtlMap mapSpecularExponent; // map_Ns (options filename) bool mapAntiAliasingTextures; // map_aat (on) MtlMap decal; // decal (options filename) MtlMap disposition; //disp (options filename) */ string::size_type pos = 0; /* Always skip spaces */ skipOptionalChars(data, pos); /* If we encounter a newmtl, create a new material object */ if (pos == data.find(MATERIAL_SENINTEL, pos)) { pos += MATERIAL_SENINTEL_LEN; MtlMaterial *mat = new MtlMaterial(); skipOptionalChars(data, pos); mat->name = data.substr(pos); materials.push_back(mat); cout << "Created material '" << mat->name << "'" << endl; return; } /* If no newmtl have been found previously then the file is erroneous, since we have nothing to add found properties to */ if (!materials.size()) { cerr << "No material yet in Mtl file, skipping line" << endl; return; } /* Use last 'newmtl' for all properties we parse */ MtlMaterial& mat = *materials.back(); string opts; /* Go through the list of valid keys */ bool keyMatched = false; for (const auto& k : keys) { string::size_type keyNameSize = string(k.keyName).length(); /* Try to match the parameter name with a valid key */ if (((data.compare(pos, keyNameSize, k.keyName)) != 0) || (data[keyNameSize] != ' ')) continue; keyMatched = true; cout << "Matched key: " << k.keyName << endl; pos += keyNameSize; skipOptionalChars(data, pos); /* Go through all the possible values for this key */ bool valueMatched = false; for (int i = 0; i < k.nrValues; ++i) { const mtlVal& v = k.values[i]; string::size_type valNameSize = (v.valName ? string(v.valName).length() : 0); /* Check if the value type matches */ if (v.valName && data.compare(pos, valNameSize, v.valName)) continue; valueMatched = true; cout << "Matched value: " << (v.valName ? v.valName : "unnamed") << endl; pos += valNameSize; skipOptionalChars(data, pos); try { float floatData[3] = {0}; int intData[3] = {0}; string stringData; vector<tuple<const mtlOpt&, void *>> optionsBuffer; /* Parse by value type */ switch (v.valType) { case VT_FLOAT: cout << "Parsing float for " << k.keyName << endl; parseOptions(data, pos, k.nrOptions, k.options, optionsBuffer); parseParamFloat(data, pos, floatData[0]); break; case VT_3FLOATS: cout << "Parsing float[3] for " << k.keyName << endl; parseOptions(data, pos, k.nrOptions, k.options, optionsBuffer); parseParam3Floats(data, pos, floatData); break; case VT_INT: cout << "Parsing int for " << k.keyName << endl; parseOptions(data, pos, k.nrOptions, k.options, optionsBuffer); parseParamInt(data, pos, intData[0]); break; case VT_STRING_AND_FLOAT: cout << "Parsing int for " << k.keyName << endl; parseOptions(data, pos, k.nrOptions, k.options, optionsBuffer); parseParamString(data, pos, stringData); break; default: cerr << "Fatal error, invalid value type (\"" << (v.valName ? v.valName : "unnamed") << "\", " << v.valType << ")" << endl; throw MtlParseException(); } /* Set to appropriate field in material object */ switch (k.keyType) { case KT_KA: mat.ambientColor = { floatData[0], floatData[1], floatData[2] }; break; case KT_KD: mat.diffuseColor = { floatData[0], floatData[1], floatData[2] }; break; case KT_KS: mat.specularColor = { floatData[0], floatData[1], floatData[2] }; break; case KT_TF: mat.transformFilter = { floatData[0], floatData[1], floatData[2] }; break; case KT_ILLUM: mat.illumination = intData[0]; break; case KT_D: mat.dissolve = floatData[0]; break; case KT_NS: mat.specularExponent = intData[0]; break; default: cerr << "Fatal error, invalid key type (" << k.keyType << ")" << endl; } } catch(exception& e) { cerr << "Failed parsing '" << k.keyName << "' value(s) from material" << endl; } /* If we have matched the parameters value with a valid key value then do not continue searching for a matching key value */ if (valueMatched) { cout << "--- DONE VAL" << endl; break; } } /* for key values */ /* If we have matched the parameter with a valid key then do not continue searching for a matching key */ if (keyMatched) { cout << "--- DONE KEY" << endl; break; } } /* for keys */ } <file_sep>/** * @copyright 2017 <NAME>, <EMAIL> */ #include <string> #include "MtlMaterial.hpp" using namespace std; MtlMaterial::MtlMaterial(const std::string& matName) : name(matName), illumination(0), dissolve(0.0f), specularExponent(0), sharpness(0.0f), opticalDensity(0.0f), mapAmbientColor("ambient"), mapDiffuseColor("diffuse"), mapSpecularColor("specular color"), mapSpecularExponent("specular exponent"), mapAntiAliasingTextures(false), decal("decal"), disposition("disposition") { ambientColor.red = 0.0f; ambientColor.green = 0.0f; ambientColor.blue = 0.0f; diffuseColor.red = 0.0f; diffuseColor.green = 0.0f; diffuseColor.blue = 0.0f; specularColor.red = 0.0f; specularColor.green = 0.0f; specularColor.blue = 0.0f; transformFilter.red = 0.0f; transformFilter.green = 0.0f; transformFilter.blue = 0.0f; } void MtlMaterial::printProperties(const string& prefix, bool isLast) { string localPrefix(string((isLast ? " " : "│")) + " ├─"); cout << prefix << (isLast ? "└─" : "├─") << "Material name: " << name << endl; cout << prefix << localPrefix << "ambientColor (Ka): " << ambientColor.red << ", " << ambientColor.green << ", " << ambientColor.blue << endl; cout << prefix << localPrefix << "diffuseColor (Kd): " << diffuseColor.red << ", " << diffuseColor.green << ", " << diffuseColor.blue << endl; cout << prefix << localPrefix << "specularColor (Ks): " << specularColor.red << ", " << specularColor.green << ", " << specularColor.blue << endl; cout << prefix << localPrefix << "Transform filter (Tf): " << transformFilter.red << ", " << transformFilter.green << ", " << transformFilter.blue << endl; cout << prefix << localPrefix << "illumination (illum): " << illumination << endl; cout << prefix << localPrefix << "dissolve (d): " << dissolve << endl; cout << prefix << localPrefix << "specularExponent (Ns): " << specularExponent << endl; cout << prefix << localPrefix << "sharpness (sharpness): " << sharpness << endl; cout << prefix << localPrefix << "opticalDensity (Ni): " << opticalDensity << endl; mapAmbientColor.printProperties(prefix + (isLast ? " " : "│")); mapDiffuseColor.printProperties(prefix + (isLast ? " " : "│")); mapSpecularColor.printProperties(prefix + (isLast ? " " : "│")); mapSpecularExponent.printProperties(prefix + (isLast ? " " : "│")); cout << prefix << localPrefix << "mapAntiAliasingTextures (map_aat): " << mapAntiAliasingTextures << endl; decal.printProperties(prefix + (isLast ? " " : "│")); disposition.printProperties(prefix + (isLast ? " " : "│"), true); } <file_sep>/** * @copyright 2017 <NAME>, <EMAIL> */ #ifndef MTLMAP_HPP #define MTLMAP_HPP #include <iostream> #include <string> enum MtlOptionImfChan { r, g, b, m, l, z }; class MtlMap { public: MtlMap(const std::string& mapName = std::string()); void printProperties(const std::string& prefix = std::string(), bool isLast = false); /** * Map name */ std::string name; /** The -blendu option turns texture blending in the horizontal direction (u direction) on or off. The default is on. */ bool blendU; // blendU (On|Off) /** The -blendv option turns texture blending in the vertical direction (v direction) on or off. The default is on. */ bool blendV; // blendV (On|Off) /** The -clamp option turns clamping on or off. When clamping is on, textures are restricted to 0-1 in the uvw range. The default is off. */ bool clamp; // clamp (On|Off) /** The -imfchan option specifies the channel used to create a scalar or bump texture. Scalar textures are applied to: transparency specular exponent decal displacement The channel choices are: r specifies the red channel. g specifies the green channel. b specifies the blue channel. m specifies the matte channel. l specifies the luminance channel. z specifies the z-depth channel. The default for bump and scalar textures is "l" (luminance), unless you are building a decal. In that case, the default is "m" (matte). */ MtlOptionImfChan imfChan; // imfchan (r|g|b|m|l|z) /** The -mm option modifies the range over which scalar or color texture values may vary. This has an effect only during rendering and does not change the file. "base" adds a base value to the texture values. A positive value makes everything brighter; a negative value makes everything dimmer. The default is 0; the range is unlimited. "gain" expands the range of the texture values. Increasing the number increases the contrast. The default is 1; the range is unlimited. */ float mm[2]; // mm (base gain) /** The -o option offsets the position of the texture map on the surface by shifting the position of the map origin. The default is 0, 0, 0. "u" is the value for the horizontal direction of the texture "v" is an optional argument. "v" is the value for the vertical direction of the texture. "w" is an optional argument. "w" is the value used for the depth of a 3D texture. */ float offset[3]; // o (u v w) /** The -s option scales the size of the texture pattern on the textured surface by expanding or shrinking the pattern. The default is 1, 1, 1. "u" is the value for the horizontal direction of the texture "v" is an optional argument. "v" is the value for the vertical direction of the texture. "w" is an optional argument. "w" is a value used for the depth of a 3D texture. "w" is a value used for the amount of tessellation of the displacement map. */ float scale[3]; // s (u v w) /** The -t option turns on turbulence for textures. Adding turbulence to a texture along a specified direction adds variance to the original image and allows a simple image to be repeated over a larger area without noticeable tiling effects. turbulence also lets you use a 2D image as if it were a solid texture, similar to 3D procedural textures like marble and granite. "u" is the value for the horizontal direction of the texture turbulence. "v" is an optional argument. "v" is the value for the vertical direction of the texture turbulence. "w" is an optional argument. "w" is a value used for the depth of the texture turbulence. By default, the turbulence for every texture map used in a material is uvw = (0,0,0). This means that no turbulence will be applied and the 2D texture will behave normally. */ float turbulence[3]; // t (u v w) /** The -texres option specifies the resolution of texture created when an image is used. The default texture size is the largest power of two that does not exceed the original image size. If the source image is an exact power of 2, the texture cannot be built any larger. If the source image size is not an exact power of 2, you can specify that the texture be built at the next power of 2 greater than the source image size. The original image should be square, otherwise, it will be scaled to fit the closest square size that is not larger than the original. Scaling reduces sharpness. */ int textureResolution[2]; // texres (string + "x" + string) /** The filename of the image to use for this map */ std::string fileName; }; #endif /* MTLMAP_HPP */ <file_sep># MtlReader Read MTL (Material Template Library, https://en.wikipedia.org/wiki/Wavefront_.obj_file) files into structures <file_sep>/** * @copyright 2017 <NAME>, <EMAIL> */ #include <iostream> #include <list> #include <string> #include "MtlObject.hpp" using namespace std; int main(int argc, char *argv[]) { MtlObject mtl("test.mtl"); mtl.printMaterials(); return 0; } <file_sep>/** * @copyright 2017 <NAME>, <EMAIL> */ #ifndef _MTLOBJECT_INT_HPP_ #define _MTLOBJECT_INT_HPP_ typedef enum mtlKeyType { KT_KA, KT_KD, KT_KS, KT_TF, KT_ILLUM, KT_D, KT_NS, KT_SHARPNESS, KT_NI, KT_MAPKA, KT_MAPKD, KT_MAPKS, KT_MAPNS, KT_MAPD, KT_DISP, KT_DECAL, KT_BUMP, KT_MAPBUMP, KT_REFL, } mtlKeyType; typedef enum mtlValType { VT_FLOAT, VT_2FLOATS, VT_3FLOATS, VT_INT, VT_2INTS, VT_3INTS, VT_STRING, VT_STRING_AND_FLOAT, VT_EMPTY, } mtlValType; typedef mtlValType mtlOptType; typedef struct mtlOpt { const char* optName; const mtlOptType optType; } mtlOpt; typedef struct mtlVal { const char* valName; const mtlValType valType; } mtlVal; typedef struct mtlKey { const char* keyName; const mtlKeyType keyType; const int nrOptions; const mtlOpt* options; const int nrValues; const mtlVal* values; } mtlKey; /** Ka, Kd, Ks and Tf 'Possible values' struct-array */ static const mtlVal kVals[] = { { "xyz", VT_3FLOATS }, { "spectral", VT_STRING_AND_FLOAT }, { nullptr, VT_3FLOATS } }; /** 'Ka, Kd, Ks, Tf' options (-o) */ static const mtlOpt kOpts = { "-o", VT_3FLOATS }; /** 'd' options (-halo) */ static const mtlOpt dOpts = { "-halo", VT_EMPTY }; /** Possible values - single int */ static const mtlVal intVal = { nullptr, VT_INT }; /** Possible values - single float */ static const mtlVal floatVal = { nullptr, VT_FLOAT }; /** A structure describing the possible MTL file material parameters and its options */ static const mtlKey keys[] = { { "Ka", KT_KA, 0, /* Number of options */ nullptr, /* Options (new mtlOpt[N]{ { "-o", VT_3FLOATS }, ... }) */ 3, /* Number of possible value-types */ kVals /* Possible values */ }, { "Kd", KT_KD, 0, nullptr, 3, kVals }, { "Ks", KT_KS, 0, nullptr, 3, kVals }, { "Tf", KT_TF, 0, nullptr, 3, kVals }, { "illum", KT_ILLUM, 0, nullptr, 1, &intVal }, { "d", KT_D, 1, &dOpts, 1, &floatVal }, { "Ns", KT_NS, 0, nullptr, 1, &intVal }, }; #endif /* _MTLOBJECT_INT_HPP_ */ <file_sep>STRIP ?= $(shell which strip) UPX ?= $(shell which upx) UPX_LEVEL ?= -9 DOXYGEN ?= $(shell which doxygen) VALGRIND ?= $(shell which valgrind) VALGRIND_OPTS ?= --tool=memcheck --leak-check=yes VALGRIND_PROG ?= $(BASE_DIR)/$(PROG) -Ux -f mac=0 DEBUG_FILE = $(BASE_DIR)/.debug NOCOMPR_FILE = $(BASE_DIR)/.nocompr PROG = mtlreader PROG_SO = libmtlreader.so prefix = /usr/bin BINDIR = /usr/local/bin INSTALL = $(prefix)/install BASE_DIR = $(shell pwd) SRCS_DIR = $(BASE_DIR)/src OBJS_DIR = $(BASE_DIR)/obj INCL_DIR = $(BASE_DIR)/include DOXYGEN_DIRS = $(BASE_DIR)/html $(BASE_DIR)/latex INCLUDES = -I$(INCL_DIR) CFLAGS += --std=c++11 -O3 -Wall -g $(INCLUDES) LDFLAGS += LIBS += SRCS = $(wildcard $(SRCS_DIR)/*.cpp) OBJS = $(patsubst $(SRCS_DIR)/%.cpp,$(OBJS_DIR)/%.o,$(SRCS)) OBJS_FPIC = $(filter-out main.o,$(patsubst $(OBJS_DIR)/%.o,$(OBJS_DIR)/%_fpic.o,$(OBJS))) DEPS = $(wildcard $(INCL_DIR)/*.hpp) STRIP_ERROR := '\e[1;33m*** ERROR: strip command not found,'\ ' no stripping has been performed ***\e[0m' UPX_ERROR := '\e[1;33m*** ERROR: upx command not found,'\ ' no compressing has been performed ***\e[0m' VALGRIND_ERROR:= '\e[1;33m*** ERROR: valgrind does not seem to be' \ ' installed on this system ***\e[0m' DOXYGEN_ERROR := '\e[1;33m*** ERROR: doxygen does not seem to be' \ ' installed on this system ***\e[0m' DEBUG_NOTE := '\e[1;33m*** NOTE: This is a DEBUG build,'\ ' no stripping or compressing has been done ***\e[0m' .PHONY: makedirs docs debug nodebug checkmem all: makedirs $(PROG) $(PROG_SO) makedirs: mkdir -p $(OBJS_DIR) $(PROG): $(OBJS) $(CXX) $(CFLAGS) $(LDFLAGS) $^ $(LIBS) -o $@ ifeq ("$(wildcard $(DEBUG_FILE))","") ifneq ("$(STRIP)","") -$(STRIP) $@ else @echo -e $(STRIP_ERROR) endif ifeq ("$(wildcard $(NOCOMPR_FILE))","") ifneq ("$(UPX)","") $(UPX) $(UPX_LEVEL) $@; true else @echo -e $(UPX_ERROR) endif endif else @echo -e $(DEBUG_NOTE) endif $(PROG_SO): $(OBJS_FPIC) $(CXX) $(CFLAGS) -shared $(LDFLAGS) $^ $(LIBS) -o $@ ifeq ("$(wildcard $(DEBUG_FILE))","") ifneq ("$(STRIP)","") -$(STRIP) $@ else @echo -e $(STRIP_ERROR) endif ifeq ("$(wildcard $(NOCOMPR_FILE))","") ifneq ("$(UPX)","") $(UPX) $(UPX_LEVEL) $@; true else @echo -e $(UPX_ERROR) endif endif else @echo -e $(DEBUG_NOTE) endif $(OBJS): $(OBJS_DIR)/%.o : $(SRCS_DIR)/%.cpp $(DEPS) $(CXX) -c $(CFLAGS) $(LDFLAGS) $< -o $@ $(OBJS_FPIC): $(OBJS_DIR)/%_fpic.o : $(SRCS_DIR)/%.cpp $(DEPS) $(CXX) -c $(CFLAGS) -fPIC $(LDFLAGS) $< -o $@ install: all $(INSTALL) -d $(BINDIR) $(INSTALL) -m 0755 $(PROG) $(BINDIR) clean: $(RM) $(PROG) $(PROG_SO) $(OBJS_DIR)/*.o *~ doxyfile.inc doxygen_sqlite3.db $(RM) -rf $(DOXYGEN_DIRS) debug: clean touch $(DEBUG_FILE) nodebug: clean $(RM) $(DEBUG_FILE) nocompress: clean touch $(NOCOMPR_FILE) compress: clean $(RM) $(NOCOMPR_FILE) checkmem: $(PROG) ifneq ("$(VALGRIND)","") $(VALGRIND) $(VALGRIND_OPTS) $(VALGRIND_PROG) else @echo -e $(VALGRIND_ERROR) endif doxyfile.inc: Makefile echo INPUT = $(INCL_DIR) $(SRCS_DIR) > doxyfile.inc echo FILE_PATTERNS = $(DEPS) $(SRCS) >> doxyfile.inc docs: doxyfile.inc $(SRCS) ifneq ("$(DOXYGEN)","") $(DOXYGEN) doxyfile.mk else @echo -e $(DOXYGEN_ERROR) endif <file_sep>/** * @copyright 2017 <NAME>, <EMAIL> */ #ifndef MTLMATERIAL_HPP #define MTLMATERIAL_HPP #include <string> #include "MtlMap.hpp" class MtlObject; struct MtlColor { float red, green, blue; }; class MtlMaterial { public: MtlMaterial(const std::string& matName = std::string()); void printProperties(const std::string& prefix = std::string(), bool isLast = false); std::string name; // newmtl (string) MtlColor ambientColor, diffuseColor, specularColor; // Ka, Kd, Ks (3 * [0 - 1]) MtlColor transformFilter; // Tf (3 * [0 - 1]) int illumination; // illum (0 - 10) (predefined meaning, enum) float dissolve; // d (0.0 - 1.0) bool dissolveHalo; // -halo (true if 'd' has '-halo' option, else false) int specularExponent; // Ns (0 - 1000) int sharpness; // sharpness (0 - 1000) float opticalDensity; // Ni (0.001 - 10.0) MtlMap mapAmbientColor; // map_Ka (options filename) MtlMap mapDiffuseColor; // map_Kd (options filename) MtlMap mapSpecularColor; // map_Ks (options filename) MtlMap mapSpecularExponent; // map_Ns (options filename) bool mapAntiAliasingTextures; // map_aat (on) MtlMap decal; // decal (options filename) MtlMap disposition; //disp (options filename) }; #endif /* MTLMATERIAL_HPP */ <file_sep>/** * @copyright 2017 <NAME>, <EMAIL> */ #include "MtlMap.hpp" using namespace std; MtlMap::MtlMap(const string& mapName) : name(mapName) {} void MtlMap::printProperties(const string& prefix, bool isLast) { cout << prefix << (isLast ? " └─" : " ├─") << "Map name: " << name << endl; }
e1f32fad9a652417c82fcecfc72547dae860892c
[ "Markdown", "Makefile", "C++" ]
11
C++
andreasbank/MtlReader
3f3b71dce520eaaab3bebbbf071ad85d6ff66479
853607e2b05844350b390ffba5e91e7ad516c3c3
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using MongoDB.Bson; using MongoDB.Driver; using MongoDB.Driver.Linq; using Orleans.Runtime; using Orleans.Transactions.Abstractions; using static Newtonsoft.Json.JsonConvert; namespace Orleans.Transactions.MongoDB.State { public class MongoDBTransactionalStateStorage<TState> : ITransactionalStateStorage<TState> where TState : class, new() { private static readonly UpdateOptions Upsert = new UpdateOptions { IsUpsert = true }; private static readonly FilterDefinitionBuilder<BsonDocument> Filter = Builders<BsonDocument>.Filter; private static readonly UpdateDefinitionBuilder<BsonDocument> Update = Builders<BsonDocument>.Update; private const string FieldId = "_id"; private const string FieldEtag = "_etag"; private readonly ILogger _logger; private readonly IGrainActivationContext _context; private readonly IMongoCollection<BsonDocument> _collection; private readonly Newtonsoft.Json.JsonSerializerSettings jsonSettings; private TransactionalStateRecord<TState> State { get; set; } public MongoDBTransactionalStateStorage( IMongoCollection<BsonDocument> collection, Newtonsoft.Json.JsonSerializerSettings jsonSettings, ILogger<MongoDBTransactionalStateStorage<TState>> logger, IGrainActivationContext context) { this._logger = logger; this._context = context; this._collection = collection; this.jsonSettings = jsonSettings; } public async Task<TransactionalStorageLoadResponse<TState>> Load() { await this.ReadRecordAsync().ConfigureAwait(false); if (string.IsNullOrEmpty(this.State.ETag)) { if (this._logger.IsEnabled(LogLevel.Debug)) this._logger.LogDebug($"{this.State.Id} Loaded v0, fresh"); // first time load return new TransactionalStorageLoadResponse<TState> { }; } if (_logger.IsEnabled(LogLevel.Debug)) _logger.LogDebug($"{this.State.Id} Loaded v{this.State.CommittedSequenceId}"); return new TransactionalStorageLoadResponse<TState>(this.State.ETag, this.State.CommittedState, this.State.CommittedSequenceId, this.State.Metadata, this.State.PendingStates); } public async Task<string> Store(string expectedETag, TransactionalStateMetaData metadata, List<PendingTransactionState<TState>> statesToPrepare, long? commitUpTo, long? abortAfter) { if (this.State.ETag != expectedETag) { throw new ArgumentException(nameof(expectedETag), "Etag does not match"); } var pendinglist = this.State.PendingStates; // abort if (abortAfter.HasValue && pendinglist.Count != 0) { var pos = pendinglist.FindIndex(t => t.SequenceId > abortAfter.Value); if (pos != -1) { pendinglist.RemoveRange(pos, pendinglist.Count - pos); } } // prepare if (statesToPrepare?.Count > 0) { foreach (var p in statesToPrepare) { var pos = pendinglist.FindIndex(t => t.SequenceId >= p.SequenceId); if (pos == -1) { pendinglist.Add(p); //append } else if (pendinglist[pos].SequenceId == p.SequenceId) { pendinglist[pos] = p; //replace } else { pendinglist.Insert(pos, p); //insert } } } // commit if (commitUpTo.HasValue && commitUpTo.Value > this.State.CommittedSequenceId) { var pos = pendinglist.FindIndex(t => t.SequenceId == commitUpTo.Value); if (pos != -1) { var committedState = pendinglist[pos]; this.State.CommittedSequenceId = committedState.SequenceId; this.State.CommittedState = committedState.State; pendinglist.RemoveRange(0, pos + 1); } else { throw new InvalidOperationException($"Transactional state corrupted. Missing prepare record (SequenceId={commitUpTo.Value}) for committed transaction."); } } await this.WriteRecordAsync().ConfigureAwait(false); if (_logger.IsEnabled(LogLevel.Debug)) _logger.LogDebug($"{this.State.Id} Stored v{this.State.CommittedSequenceId} eTag={this.State.ETag}"); return this.State.ETag; } public async Task ReadRecordAsync() { var grainKey = this._context.GrainInstance.GrainReference.ToShortKeyString(); var filter = new BsonDocument(FieldId, grainKey); var doc = await this._collection.Find(filter) .FirstOrDefaultAsync().ConfigureAwait(false); if (doc == null) this.State = new TransactionalStateRecord<TState> { Id = grainKey }; else { this.State = new TransactionalStateRecord<TState> { Id = doc[FieldId].AsString, ETag = doc[FieldEtag].AsString, CommittedState = DeserializeObject<TState>(doc[nameof(State.CommittedState)].AsString, this.jsonSettings), CommittedSequenceId = doc[nameof(State.CommittedSequenceId)].AsInt64, Metadata = DeserializeObject<TransactionalStateMetaData>(doc[nameof(State.Metadata)].AsString, this.jsonSettings), PendingStates = DeserializeObject<List<PendingTransactionState<TState>>>(doc[nameof(State.PendingStates)].AsString, this.jsonSettings) }; } } public async Task WriteRecordAsync() { var grainKey = this._context.GrainInstance.GrainReference.ToShortKeyString(); var eTag = this.State.ETag; this.State.ETag = Guid.NewGuid().ToString(); var ret = await this._collection.UpdateOneAsync( Filter.And( Filter.Eq(FieldId, grainKey), Filter.Eq(FieldEtag, eTag) ), Update .Set(FieldEtag, this.State.ETag) .Set(nameof(this.State.CommittedState), SerializeObject(this.State.CommittedState, this.jsonSettings)) .Set(nameof(this.State.CommittedSequenceId), this.State.CommittedSequenceId) .Set(nameof(this.State.Metadata), SerializeObject(this.State.Metadata, this.jsonSettings)) .Set(nameof(this.State.PendingStates), SerializeObject(this.State.PendingStates, this.jsonSettings)) , Upsert).ConfigureAwait(false); } } [Serializable] public class TransactionalStateRecord<TState> where TState : class, new() { public string Id; public string ETag { get; set; } public TState CommittedState { get; set; } = new TState(); public long CommittedSequenceId { get; set; } public TransactionalStateMetaData Metadata { get; set; } = new TransactionalStateMetaData(); public List<PendingTransactionState<TState>> PendingStates { get; set; } = new List<PendingTransactionState<TState>>(); } } <file_sep> namespace Orleans.Configuration { public class MongoDBTransactionalStateOptions { public string ConnectionString { get; set; } public string Database { get; set; } } } <file_sep>using System; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Orleans.Configuration; using Orleans.Providers; using Orleans.Runtime; using Orleans.Transactions.Abstractions; using Orleans.Transactions.MongoDB.State; namespace Orleans.Hosting { public static class MongoDBTransactionsSiloBuilderExtensions { /// <summary> /// Configure silo to use MongoDB as the default transactional grain storage. /// </summary> public static ISiloHostBuilder AddMongoDBTransactionalStateStorageAsDefault(this ISiloHostBuilder builder, Action<MongoDBTransactionalStateOptions> configureOptions) { return builder.AddMongoDBTransactionalStateStorage(ProviderConstants.DEFAULT_STORAGE_PROVIDER_NAME, configureOptions); } /// <summary> /// Configure silo to use MongoDB for transactional grain storage. /// </summary> public static ISiloHostBuilder AddMongoDBTransactionalStateStorage(this ISiloHostBuilder builder, string name, Action<MongoDBTransactionalStateOptions> configureOptions) { return builder.ConfigureServices(services => services.AddMongoDBTransactionalStateStorage(name, ob => ob.Configure(configureOptions))); } /// <summary> /// Configure silo to use MongoDB as the default transactional grain storage. /// </summary> public static ISiloHostBuilder AddMongoDBTransactionalStateStorageAsDefault(this ISiloHostBuilder builder, Action<OptionsBuilder<MongoDBTransactionalStateOptions>> configureOptions = null) { return builder.AddMongoDBTransactionalStateStorage(ProviderConstants.DEFAULT_STORAGE_PROVIDER_NAME, configureOptions); } /// <summary> /// Configure silo to use MongoDB for transactional grain storage. /// </summary> public static ISiloHostBuilder AddMongoDBTransactionalStateStorage(this ISiloHostBuilder builder, string name, Action<OptionsBuilder<MongoDBTransactionalStateOptions>> configureOptions = null) { return builder.ConfigureServices(services => services.AddMongoDBTransactionalStateStorage(name, configureOptions)); } private static IServiceCollection AddMongoDBTransactionalStateStorage(this IServiceCollection services, string name, Action<OptionsBuilder<MongoDBTransactionalStateOptions>> configureOptions = null) { configureOptions?.Invoke(Configuration.OptionsServiceCollectionExtensions.AddOptions<MongoDBTransactionalStateOptions>(services, name)); services.TryAddSingleton<ITransactionalStateStorageFactory>(sp => sp.GetServiceByName<ITransactionalStateStorageFactory>(ProviderConstants.DEFAULT_STORAGE_PROVIDER_NAME)); services.AddSingletonNamedService<ITransactionalStateStorageFactory>(name, MongoDBTransactionalStateStorageFactory.Create); return services; } } } <file_sep>using System; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using MongoDB.Bson; using MongoDB.Driver; using Orleans.Configuration; using Orleans.Runtime; using Orleans.Transactions.Abstractions; namespace Orleans.Transactions.MongoDB.State { public class MongoDBTransactionalStateStorageFactory : ITransactionalStateStorageFactory { private readonly string name; private readonly ClusterOptions clusterOptions; private readonly ILoggerFactory loggerFactory; private readonly IMongoDatabase db; private readonly Newtonsoft.Json.JsonSerializerSettings jsonSettings; public static ITransactionalStateStorageFactory Create(IServiceProvider services, string name) { var optionsSnapshot = services.GetRequiredService<IOptionsSnapshot<MongoDBTransactionalStateOptions>>(); var op = optionsSnapshot.Get(name); return ActivatorUtilities.CreateInstance<MongoDBTransactionalStateStorageFactory>(services, name, op); } public MongoDBTransactionalStateStorageFactory(string name, MongoDBTransactionalStateOptions options, IOptions<ClusterOptions> clusterOptions, ITypeResolver typeResolver, IGrainFactory grainFactory, ILoggerFactory loggerFactory) { this.name = name; this.jsonSettings = TransactionalStateFactory.GetJsonSerializerSettings( typeResolver, grainFactory); var client = new MongoClient(options.ConnectionString); db = client.GetDatabase(options.Database); this.clusterOptions = clusterOptions.Value; this.loggerFactory = loggerFactory; } public ITransactionalStateStorage<TState> Create<TState>(string stateName, IGrainActivationContext context) where TState : class, new() { return ActivatorUtilities.CreateInstance<MongoDBTransactionalStateStorage<TState>>( context.ActivationServices, this.db.GetCollection<BsonDocument>("tsr_" + stateName), jsonSettings); } } }
e6bedd59ea780e8ff73f6227ecf8d18a35e108d5
[ "C#" ]
4
C#
csyszf/Orleans.Transactions.MongoDB
5e2148ed6322f3e036f71d5214a6e7bbb9439ed9
d1777f0e069b28fc3c97775379642258af1e2ee7
refs/heads/master
<file_sep>import React, { useState } from 'react'; import { TextInput, View, Button, TouchableOpacity } from 'react-native'; import { adicionarProdutos } from '../../data/produto/produto_db' import Icon from 'react-native-vector-icons/SimpleLineIcons'; export function Cadastro({ navigation }) { const [nome, setNome] = useState(null); const [descricao, setDescricao] = useState(null); const [preco, setPreco] = useState(null); function salvarProduto() { adicionarProdutos(nome, descricao, parseInt(preco)) } return ( <View> <TouchableOpacity style={{ width: 44, height: 44, margin: 20, top: 0 }} onPress={() => navigation.openDrawer()}> <Icon name='menu' size={20} color='black' /> </TouchableOpacity> <TextInput placeholder='Nome do Produto' onChangeText={nome => setNome(nome)} value={nome} /> <TextInput placeholder='Descrição do Produto' onChangeText={descricao => setDescricao(descricao)} value={descricao} /> <TextInput placeholder='Preço do Produto' onChangeText={preco => setPreco(preco)} value={preco} /> <Button title='Salvar' onPress={salvarProduto} /> </View> ); }<file_sep>import React, { useState, useContext, useEffect } from 'react'; import { SafeAreaView, View, Text, FlatList, TouchableOpacity, Image } from 'react-native'; import { Card } from 'react-native-elements'; import { styles } from './styles'; import { listarFavoritos, adicionarFavoritos, deleteFavorito } from '../../data/favoritos_db' import { CartContext } from '../../context/CartProvider'; import { Icon } from 'react-native-elements'; import Icon2 from 'react-native-vector-icons/AntDesign'; import { ScrollView } from 'react-native-gesture-handler'; export const Favoritos = () => { const [favorito, setFavorito] = useState(listarFavoritos()) const { cart, addItem, removeItem, clearCart, count, count3 } = useContext(CartContext) const [quantidadeTotal, setQuantidadeTotal] = useState(0) const [cartItems, setCartItems] = useState(0); const [favorite, setFavorite] = useState(0); const [state, setState] = useState(0); useEffect(() => { }, [favorito.length]) useEffect(() => { var soma = cart.reduce(function (accumulator, currentValue) { return accumulator + currentValue.quantidade; }, 0); setQuantidadeTotal(soma) }, [cartItems]) useEffect(() => { }, [count3]) function countCart(nome, descricao, preco, url) { count() setCartItems(cartItems + 1) addItem(nome, descricao, preco, url) } return ( <SafeAreaView> <ScrollView> <FlatList data={favorito} extraData={favorito} keyExtractor={item => item.id} renderItem={({ item }) => { return ( <View style={styles.listItem}> <Image source={{ uri: item.favorito_url }} style={styles.productImage} /> <View style={styles.productInfo}> <Text style={styles.listItemText}>{item.favorito_nome}</Text> </View> <View style={styles.productInfo}> <Text style={styles.listItemText}>R$ {item.favorito_preco}</Text> </View> <View> <TouchableOpacity style={styles.btnAddCart} onPress={() => { countCart(item.favorito_nome, item.favorito_descricao, item.favorito_preco, item.favorito_url) }} > <Icon name="add-circle-outline" type="ionicon" size={36} color='#ff531a' /> </TouchableOpacity> <TouchableOpacity style={styles.btnAddCart} onPress={() => { setFavorite(favorite + 1), deleteFavorito(item.favorito_id) }} > <Icon2 name="star" size={36} color='#ff531a' /> </TouchableOpacity> </View> </View> ) }} /> </ScrollView> </SafeAreaView> ) }<file_sep>import * as React from 'react'; import { NavigationContainer } from '@react-navigation/native'; import { CartProvider } from './context/CartProvider'; import { DrawerNavigation } from './navigation' function App() { return ( <NavigationContainer> <CartProvider> <DrawerNavigation /> </CartProvider> </NavigationContainer> ); } export default App;<file_sep>import React, { useState, useEffect } from 'react'; import { SafeAreaView, View, Text, FlatList, TouchableOpacity, Modal, TextInput, Button, Alert } from 'react-native'; import { deleteProduto, listarProdutos, atualizarProduto, adicionarProdutos } from '../../data/produto/produto_db' import Icon from 'react-native-vector-icons/MaterialCommunityIcons'; import Icon1 from 'react-native-vector-icons/MaterialIcons'; import Icon2 from 'react-native-vector-icons/Ionicons'; import { ScrollView } from 'react-native-gesture-handler'; export const Products = () => { const [produtos, setProdutos] = useState(listarProdutos()) const [data, setData] = useState(false) const [modalVisible, setModalVisible] = useState(false); const [modalVisible1, setModalVisible1] = useState(false); const [nome, setNome] = useState(null); const [descricao, setDescricao] = useState(null); const [preco, setPreco] = useState(null); function deleteP(produto_id) { deleteProduto(produto_id) setData(!data) } function edit(produto_id) { console.log(nome, descricao, preco) if (nome == '' || descricao == '' || preco == '') { Alert.alert( "Erro", "Campo(s) vazio(s)", [ { text: "Cancel", onPress: () => setModalVisible(false), style: "cancel" }, { text: "OK", onPress: () => console.log("OK Pressed") } ] ); return } else if ((nome == null || descricao == null || preco == null)) { setModalVisible(false) return } atualizarProduto(produto_id, nome, descricao, parseInt(preco)) setModalVisible(false) setData(!data) } function salvarProduto() { if (nome == '' || descricao == '' || preco == '' || nome == null || descricao == null || preco == null) { Alert.alert( "Erro", "Campo(s) vazio(s)", [ { text: "Cancel", onPress: () => setModalVisible(false), style: "cancel" }, { text: "OK", onPress: () => console.log("OK Pressed") } ] ); return } adicionarProdutos(nome, descricao, parseInt(preco)) setModalVisible1(false) setData(!data) setNome('') setDescricao('') setPreco('') } return ( <SafeAreaView> <FlatList style={{backgroundColor:'purple'}} data={produtos} keyExtractor={(item, index) => index.toString()} renderItem={({ item, index }) => { return ( <ScrollView style={{padding: 20}}> <View style={{flexDirection: 'row', justifyContent: 'space-between'}}> <Text style={{flexDirection: 'column'}}>{item.produto_nome}</Text> <Text style={{flexDirection: 'column'}}>{item.produto_descricao}</Text> <Text style={{flexDirection: 'column'}}>{item.produto_preco}</Text> <TouchableOpacity style={{ width: 44, height: 44, top: 0, flexDirection: 'column' }} onPress={() => deleteP(item.produto_id)}> <Icon name='delete' size={20} color='black' /> </TouchableOpacity> <TouchableOpacity style={{ width: 44, height: 44, top: 0, flexDirection: 'column' }} onPress={() => setModalVisible(true)}> <Icon1 name='edit' size={20} color='black' /> </TouchableOpacity> <Modal animationType="fade" visible={modalVisible} > <TextInput placeholder='Nome do Produto' onChangeText={nome => setNome(nome)} defaultValue={item.produto_nome} maxLength={20}/> <TextInput placeholder='Descrição do Produto' onChangeText={descricao => setDescricao(descricao)} defaultValue={item.produto_descricao}maxLength={20} /> <TextInput placeholder='Preço do Produto' onChangeText={preco => setPreco(preco)} defaultValue={item.produto_preco.toString()} keyboardType="number-pad"maxLength={20} /> <Button title='Salvar' onPress={() => edit(item.produto_id)} /> <Button title='Cancelar' onPress={() => setModalVisible(false)} /> </Modal> </View> </ScrollView> ) }} extraData={data} /> <Modal animationType="fade" visible={modalVisible1}> <TextInput placeholder='Nome do Produto' onChangeText={nome => setNome(nome)} maxLength={10} /> <TextInput placeholder='Descrição do Produto' onChangeText={descricao => setDescricao(descricao)} maxLength={10} /> <TextInput placeholder='Preço do Produto' onChangeText={preco => setPreco(preco)} maxLength={10} keyboardType="number-pad"/> <Button title='Salvar' onPress={salvarProduto} /> <Button title='Cancelar' onPress={() => setModalVisible1(false)} /> </Modal> <View> <TouchableOpacity style={{ margin: 20, marginRight: 20, bottom: 0, alignSelf: 'flex-end', }} onPress={() => setModalVisible1(true)}> <Icon2 name='add-circle-outline' size={60} color='black' /> </TouchableOpacity> </View> </SafeAreaView> ) } <file_sep>import Realm from 'realm' class FavoritosSchema extends Realm.Object { } FavoritosSchema.schema = { name: 'Favorito3', properties: { favorito_id: 'int', favorito_nome: 'string', favorito_descricao: 'string', favorito_preco: 'string', favorito_url: 'string' }, primaryKey: 'favorito_id' }; class Login extends Realm.Object { } Login.schema = { name: 'Login2', properties: { login_id: 'int', login_email: 'string', login_senha: 'string', }, primaryKey: 'login_id' }; let realm = new Realm({ schema: [FavoritosSchema, Login] }); export default realm; const listarLogins = (email_user, senha_user) => { let sla = false let count = 0 realm.objects('Login2').filter(item => { sla = email_user === item.login_email && senha_user === item.login_senha sla === true ? count += 1 : count console.log(count, sla); }); if(count == 1){ return true }else{ return false } } let adicionarLogins = (email, senha) => { let sla = false let count = 0 realm.objects('Login2').filter(item => { sla = email === item.login_email sla === true ? count += 1 : count console.log(count, sla); }); if(count == 1){ return true } console.log(email, senha); const ultimoId = realm.objects('Login2').sorted('login_id', true)[0]; const maiorId = ultimoId == null ? 0 : ultimoId.login_id; const proximoId = maiorId == null ? 1 : maiorId + 1; realm.write(() => { const prod = realm.create('Login2', { login_id: proximoId, login_email: email, login_senha: senha, }); }); return false; } let listarFavoritos = () => { return realm.objects('Favorito3'); } let adicionarFavoritos = (nome, descricao, preco, id, url) => { console.log(nome, descricao, preco); realm.write(() => { const prod = realm.create('Favorito3', { favorito_id: id, favorito_nome: nome, favorito_descricao: descricao, favorito_preco: preco, favorito_url:url }); }); } let deleteFavorito = (id) => { console.log(id); realm.write(() => { let deleteItem = realm.objectForPrimaryKey('Favorito3', id); realm.delete(deleteItem); }); } export { listarFavoritos, adicionarFavoritos, deleteFavorito, listarLogins, adicionarLogins }<file_sep>import * as React from 'react'; import { View, TouchableOpacity } from 'react-native'; import Icon from 'react-native-vector-icons/SimpleLineIcons'; import { createDrawerNavigator } from '@react-navigation/drawer'; import { NavigationContainer } from '@react-navigation/native'; const Drawer = createDrawerNavigator(); export const Hamburger = ({ navigation }) => { return ( <TouchableOpacity style={{ width: 44, height: 44, margin: 20, top: 0 }} onPress={() => navigation.openDrawer()}> <Icon name='menu' size={20} color='black' /> </TouchableOpacity> ) } <file_sep>import React, { useEffect, useState, useContext } from 'react'; import { SafeAreaView, View, Text, ActivityIndicator, TouchableOpacity, FlatList, Modal, Alert, Image } from 'react-native'; import styles from './styles'; import { Icon } from 'react-native-elements'; import axios from 'axios'; import { CartContext } from '../../context/CartProvider'; import Icon2 from 'react-native-vector-icons/AntDesign'; import { adicionarFavoritos, deleteFavorito, listarFavoritos } from '../../data/favoritos_db'; export const Categoria = ({ navigation }) => { const [categorias, setCategorias] = useState([]); const [isLoading, setIsLoading] = useState(false); const [modal, setModal] = useState(false); const [produtos, setProdutos] = useState([]); const [produto1, setProduto1] = useState([]); const { cart, addItem, removeItem, clearCart, count, count4 } = useContext(CartContext) const [quantidadeTotal, setQuantidadeTotal] = useState(0) const [cartItems, setCartItems] = useState(0); const [arrayteste, setArrayteste] = useState(listarFavoritos); useEffect(() => { getProdutos(); }, []); getProdutos = (key) => { setIsLoading(true); axios.get('https://residencia-ecommerce.herokuapp.com/produto') .then((response) => { setProdutos(response.data); response.data.map(produto => { if (key == produto.categoria.id) { produto1.push(produto) } }) setIsLoading(false); }).catch(function (error) { setIsLoading(false); }); } useEffect(() => { var soma = cart.reduce(function (accumulator, currentValue) { return accumulator + currentValue.quantidade; }, 0); setQuantidadeTotal(soma) }, [cartItems]) function countCart(nome, descricao, preco, url) { count() setCartItems(cartItems + 1) addItem(nome, descricao, preco, url) } function teste(nome, descricao, valorUnitario, url, id, item) { var teste = 0; console.log(arrayteste.length); if (arrayteste.length == 0) { console.log('aqui1'); adicionarFavoritos(nome, descricao, valorUnitario, id, url); Alert.alert( "Produto Adicionado", "Produto adicionado aos favoritos", [ { text: "OK", onPress: () => { teste = 0, console.log(teste) } } , { text: "Ir para Favoritos", onPress: () => { setModal(false), teste = 0, navigation.navigate('Favoritos') } } ] ); return } arrayteste.map(produto => { if (produto.favorito_id == id) { console.log('aqui2'); teste += 1; deleteFavorito(id); Alert.alert( "Produto Removido", "Produto removido dos favoritos", [ { text: "OK", onPress: () => { teste = 0, console.log(teste) } } , { text: "Ir para Favoritos", onPress: () => { setModal(false), teste = 0, navigation.navigate('Favoritos') } } ] ); } }) if (teste === 0) { console.log('aqui3'); adicionarFavoritos(nome, descricao, valorUnitario, id, url); Alert.alert( "Produto Adicionado", "Produto adicionado aos favoritos", [ { text: "OK", onPress: () => { teste = 0, console.log(teste) } } , { text: "Ir para Favoritos", onPress: () => { setModal(false), teste = 0, navigation.navigate('Favoritos') } } ] ); return } } getCategorias = () => { setIsLoading(true); axios.get('https://residencia-ecommerce.herokuapp.com/categoria') .then((response) => { setCategorias(response.data); setIsLoading(false); }).catch(function (error) { setIsLoading(false); }); } useEffect(() => { getCategorias(); }, []); return ( <SafeAreaView> {(isLoading) ? <View> <ActivityIndicator size="large" color="#5500dc" /> </View> : <FlatList style={{ margin: 10 }} data={categorias} keyExtractor={item => item.id} renderItem={({ item }) => { return ( <View style={styles.categoriaItem}> <View style={styles.categoriaInfo}> <Text style={styles.categoriaText}>{item.nome}</Text> </View> <View> <TouchableOpacity style={styles.btnListarProd} onPress={() => { setModal(true), getProdutos(item.id) }} > <Icon name="caret-forward-outline" type="ionicon" size={36} color='black' /> </TouchableOpacity> </View> <View> <Modal animationType="fade" visible={modal}> <TouchableOpacity onPress={() => { setModal(false), setProduto1([]) }} style={styles.button}> <Text> Fechar </Text> </TouchableOpacity> <FlatList style={{ margin: 10 }} data={produto1} extraData={produto1} keyExtractor={item => item.id} renderItem={({ item }) => { return ( <View style={styles.listItem}> <Image source={{ uri: item.url }} style={styles.productImage} /> <View style={styles.productInfo}> <Text style={styles.listItemText}>{item.nome}</Text> </View> <View style={styles.productInfo}> <Text style={styles.listItemText}>R$ {item.valorUnitario}</Text> </View> <View> <TouchableOpacity style={styles.btnAddCart} onPress={() => { countCart(item.nome, item.descricao, item.valorUnitario, item.url) }} > <Icon name="add-circle-outline" type="ionicon" size={36} color='#ff531a' /> </TouchableOpacity> <TouchableOpacity style={styles.btnAddCart} onPress={() => { teste(item.nome, item.descricao, item.valorUnitario.toString(), item.url, item.id, item), count4() }} > <Icon2 name="star" size={36} color='#ff531a' /> </TouchableOpacity> </View> </View> ) }} /> </Modal> </View> </View> ) }} /> } </SafeAreaView> ); } <file_sep>import { StyleSheet } from 'react-native' export const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#ff531a' }, header: { flex: 1, justifyContent: 'flex-end', paddingHorizontal: 20, paddingBottom: 50, backgroundColor: '#ff531a' }, footer: { flex: 3, backgroundColor: '#fff', borderTopLeftRadius: 30, borderTopRightRadius: 30, paddingHorizontal: 20, paddingVertical: 30 }, text_header: { color: '#000000', fontWeight: 'bold', fontSize: 30, textAlign: 'center' }, text_footer: { color: '#05375a', fontSize: 18 }, input_container: { marginTop: 20, flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }, actionError: { borderColor: 'red' }, textInput: { flex: 1, paddingTop: 10, paddingRight: 0, paddingBottom: 10, paddingLeft: 10, backgroundColor: '#fff', color: '#05375a', borderWidth: 2, borderStyle: 'solid', borderRadius: 50, }, errorMsg: { borderColor: 'black', }, button: { alignItems: 'center', marginTop: 20, backgroundColor: '#ff531a', borderRadius: 50, padding: 15 }, button_container: { marginTop: 20, }, switch_container: { flexDirection: 'row', alignItems: 'center', textAlign: 'center', marginTop: 10, }, signup_container: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', textAlign: 'center', marginTop: 10 } });<file_sep>import Realm from 'realm' class ProdutoSchema extends Realm.Object { } ProdutoSchema.schema = { name: 'Produto1', properties: { produto_id: 'int', produto_nome: 'string', produto_descricao: 'string', produto_preco: 'int' }, primaryKey: 'produto_id' }; let realm_produto = new Realm({ schema: [ProdutoSchema] }); export default realm_produto; let listarProdutos = () => { return realm_produto.objects('Produto1'); } let adicionarProdutos = (nome, descricao, preco) => { console.log(nome, descricao, preco); const ultimoId = realm_produto.objects('Produto1').sorted('produto_id', true)[0]; const maiorId = ultimoId == null ? 0 : ultimoId.produto_id; const proximoId = maiorId == null ? 1 : maiorId + 1; realm_produto.write(() => { const prod = realm_produto.create('Produto1', { produto_id: proximoId, produto_nome: nome, produto_descricao: descricao, produto_preco: preco }); }); } let deleteProduto = (id) => { console.log(id); realm_produto.write(() => { let deleteItem = realm_produto.objectForPrimaryKey('Produto1', id); realm_produto.delete(deleteItem); }); } let atualizarProduto = (id, nome, descricao, preco) => { realm_produto.write(() => { const person = realm_produto.create( "Produto1", { produto_id: id, produto_nome: nome, produto_descricao: descricao, produto_preco: preco }, "modified" ); }); } export { listarProdutos, adicionarProdutos, deleteProduto, atualizarProduto } <file_sep>import React, { useEffect, useState } from 'react'; import axios from 'axios'; import { FlatList, Text, View, Image, ActivityIndicator, StyleSheet, Header, SafeAreaView } from 'react-native'; import { Card } from 'react-native-elements'; const Passageiros = () => { const [passageiros, setPassageiros] = useState([]); const [loading, setLoading] = useState(false); const [page, setPage] = useState(0); useEffect(() => { getPassageiros() }, []) getPassageiros = async () => { setLoading(true) await axios.get(`https://api.instantwebtools.net/v1/passenger?page=${page}&size=10`) .then((response) => { setLoading(true) console.log(response.data) setPassageiros([...passageiros, ...response.data.data]); setPage(page + 1) setLoading(false) }).catch(function (error) { console.log(error); }) } renderFooter = () => { if (!loading) return null; return ( <View > <ActivityIndicator size="large" color="#00ff00" /> </View> ); }; return ( <SafeAreaView> <FlatList onEndReached={getPassageiros} onEndReachedThreshold={0.1} ListFooterComponent={renderFooter} style={{ marginTop: 30, marginBottom: 30 }} data={passageiros} keyExtractor={(item, index) => index.toString()} renderItem={({ item, index }) => { return ( <ScrollView> <Card containerStyle={{ justifyContent: 'center', backgroundColor: '#00BCD4', alignItems: 'center', marginBottom: 20 }}> <Card.Title>Dados</Card.Title> <Card.Divider /> <Card.Image source={{ uri: item.airline.logo }} style={{ display: 'flex', width: 50, height: 50, resizeMode: 'stretch', }} ></Card.Image> <Text>Nome: {item.name}</Text> <Text>Qtde. Viagens: {item.trips}</Text> <Text>Cia. Aérea: {item.airline.name}</Text> </Card> </ScrollView> ) }} /> </SafeAreaView> ); }; export default Passageiros const styles = StyleSheet.create({ list: { paddingHorizontal: 20, }, listItem: { backgroundColor: '#EEE', marginTop: 20, padding: 30, }, loading: { alignSelf: 'center', marginVertical: 20, backgroundColor: 'blue' }, });<file_sep>import React, { useEffect, useState, useContext } from 'react'; import { Image, Text, View, FlatList, SafeAreaView, ActivityIndicator, TouchableOpacity, Alert } from 'react-native'; import axios from 'axios'; import { useNavigation } from '@react-navigation/native'; import { Icon } from 'react-native-elements'; import { CartContext } from '../../context/CartProvider'; import { adicionarFavoritos, deleteFavorito, listarFavoritos } from '../../data/favoritos_db'; import Icon2 from 'react-native-vector-icons/AntDesign'; import styles from './styles'; export const Home = ({ navigation }) => { const [produtos, setProdutos] = useState([]); const [isLoading, setIsLoading] = useState(false); const { cart, addItem, removeItem, clearCart, count, count4 } = useContext(CartContext) const [quantidadeTotal, setQuantidadeTotal] = useState(0) const [cartItems, setCartItems] = useState(0); const [favorite, setFavorite] = useState(0); const [arrayteste, setArrayteste] = useState(listarFavoritos); useEffect(() => { getProdutos(); }, []); getProdutos = () => { setIsLoading(true); axios.get('https://residencia-ecommerce.herokuapp.com/produto') .then((response) => { //console.log(response.data); setProdutos(response.data); setIsLoading(false); }).catch(function (error) { console.log(error); setIsLoading(false); }); } useEffect(() => { var soma = cart.reduce(function (accumulator, currentValue) { return accumulator + currentValue.quantidade; }, 0); setQuantidadeTotal(soma) }, [cartItems]) function countCart(nome, descricao, preco, url) { count() setCartItems(cartItems + 1) addItem(nome, descricao, preco, url) } function teste(nome, descricao, valorUnitario, url, id, item) { var teste = 0; console.log(arrayteste.length); if (arrayteste.length == 0) { console.log('aqui1'); adicionarFavoritos(nome, descricao, valorUnitario, id, url); Alert.alert( "Produto Adicionado", "Produto adicionado aos favoritos", [ { text: "OK", onPress: () => { teste = 0, console.log(teste) } } , { text: "Ir para Favoritos", onPress: () => { teste = 0, navigation.navigate('Favoritos') } } ] ); return } arrayteste.map(produto => { if (produto.favorito_id == id) { console.log('aqui2'); teste += 1; deleteFavorito(id); Alert.alert( "Produto Removido", "Produto removido dos favoritos", [ { text: "OK", onPress: () => { teste = 0, console.log(teste) } } , { text: "Ir para Favoritos", onPress: () => { teste = 0, navigation.navigate('Favoritos') } } ] ); } }) if (teste === 0) { console.log('aqui3'); adicionarFavoritos(nome, descricao, valorUnitario, id, url); Alert.alert( "Produto Adicionado", "Produto adicionado aos favoritos", [ { text: "OK", onPress: () => { teste = 0, console.log(teste) } } , { text: "Ir para Favoritos", onPress: () => { teste = 0, navigation.navigate('Favoritos') } } ] ); return } } return ( <SafeAreaView> {(isLoading) ? <View style={styles.containerAct}> <ActivityIndicator size="large" color="#5500dc" /> </View> : <FlatList data={produtos} keyExtractor={item => item.id} renderItem={({ item }) => { return ( <View style={styles.listItem}> <Image source={{ uri: item.url }} style={styles.productImage} /> <View style={styles.productInfo}> <Text style={styles.listItemText}>{item.nome}</Text> </View> <View style={styles.productInfo}> <Text style={styles.listItemText}>R$ {item.valorUnitario}</Text> </View> <View> <TouchableOpacity style={styles.btnAddCart} onPress={() => { countCart(item.nome, item.descricao, item.valorUnitario, item.url) }} > <Icon name="add-circle-outline" type="ionicon" size={36} color='#ff531a' /> </TouchableOpacity> <TouchableOpacity style={styles.btnAddCart} onPress={() => { teste(item.nome, item.descricao, item.valorUnitario.toString(), item.url, item.id, item), count4() }} > <Icon2 name="star" size={36} color='#ff531a' /> </TouchableOpacity> </View> </View> ) }} /> } </SafeAreaView> ); }; <file_sep>import React, { useState, useEffect } from "react"; import { Button, View, Text, TextInput } from "react-native"; import styles from './styles' const Calc = () => { const [num1, setNum1] = useState(''); const [num2, setNum2] = useState(''); const [total, setTotal] = useState(0); const [operator, setOperator] = useState(''); function result() { if (operator === "+") { setTotal(parseFloat(num1) + parseFloat(num2)) } else if (operator === "-") { setTotal(parseFloat(num1) - parseFloat(num2)) } else if (operator === "x") { setTotal(parseFloat(num1) * parseFloat(num2)) } else { setTotal(parseFloat(num1) / parseFloat(num2)) } } return ( <View style = {styles.container}> <TextInput style = {styles.input} placeholder='Insira o primeiro numero' keyboardType='numeric' onChangeText={(text) => setNum1(text)} value={num1} /> <View style = {styles.botao}> <Button onPress={() => setOperator("+")} title=" + " /> <Button onPress={() => setOperator("-")} title=" - " /> <Button onPress={() => setOperator("x")} title=" x " /> <Button onPress={() => setOperator("/")} title=" / " /> </View> <TextInput style = {styles.input} placeholder='Insira o segundo numero' keyboardType='numeric' onChangeText={(text) => setNum2(text)} value={num2} /> <View style = {styles.equalButton}> <Button onPress={result} title="=" /> </View> <Text style = {styles.num}>{total}</Text> </View> ) } export default Calc<file_sep>import * as React from 'react'; import { ScrollView } from 'react-native'; import { View, Text, TouchableOpacity, TextInput, Switch, Modal, Alert } from 'react-native'; import { adicionarLogins, listarLogins } from '../../data/favoritos_db'; import { styles } from './styles'; import { CartContext } from '../../context/CartProvider'; import { Categoria } from '../Categoria'; export const Login = ({ navigation }) => { const [passwd, setPasswd] = React.useState(true) const [modalVisible, setModalVisible] = React.useState(false); const [senha, setSenha] = React.useState(null); const [senha0, setSenha0] = React.useState(null); const [senha1, setSenha1] = React.useState(null); const [email, setEmail] = React.useState(null); const [email1, setEmail1] = React.useState(null); const [erro, setErro] = React.useState(false); const [erro1, setErro1] = React.useState(false); const { login, log } = React.useContext(CartContext) function salvarLogin() { if (senha0 == '' || email1 == '' || senha1 == '' || senha0 == null || email1 == null || senha1 == null) { Alert.alert( "Erro", "Há Campo(s) vazio(s)", [ { text: "OK", onPress: () => console.log("OK Pressed") } ] ); setErro1(true) return } if (senha0 == senha1) { if (adicionarLogins(email1, senha1) == true) { Alert.alert( "Erro", "Email já existente", [ { text: "OK", onPress: () => console.log("OK Pressed") } ] ); setSenha0('') setSenha1('') setErro1(true) return } else { setEmail1('') setSenha0('') setSenha1('') setErro1(false) setModalVisible(false) Alert.alert( "Sucesso", "Cadastro Realizado Com Sucesso", [ { text: "OK", onPress: () => console.log("OK Pressed") } ] ); } } else { Alert.alert( "Erro", "Senhas não batem", [ { text: "OK", onPress: () => console.log("OK Pressed") } ] ); setSenha0('') setSenha1('') setErro1(true) return } } function verificarLogin() { if (listarLogins(email, senha) === true) { login(true) Alert.alert( "Correto", "Login Correto", [ { text: "OK", onPress: () => navigation.navigate('Categoria') } ] ); return } else { Alert.alert( "Erro", "Login Errado", [ { text: "OK", onPress: () => console.log("OK Pressed") } ] ); setErro(true) setSenha('') return } } return ( <View style={styles.container}> <View style={styles.header}> <Text style={styles.text_header}>Faça seu Login Aqui!</Text> </View> <View style={styles.footer}> <View style={styles.input_container}> <TextInput placeholder="Email" placeholderTextColor={erro ? 'red' : 'gray'} style={[styles.textInput, erro ? styles.actionError : styles.errorMsg]} onChangeText={email => { setEmail(email), setErro(false) }} value={email != '' ? email : ''} /> </View> <View style={styles.input_container}> <TextInput placeholder="Password" placeholderTextColor={erro ? 'red' : 'gray'} style={[styles.textInput, erro ? styles.actionError : styles.errorMsg]} secureTextEntry={passwd} onChangeText={senha => { setSenha(senha), setErro(false) }} value={senha != '' ? senha : ''} /> </View> <View style={styles.switch_container}> <Switch trackColor={{ false: "#767577", true: "#ff531a" }} thumbColor={passwd ? "#fff" : "orange"} ios_backgroundColor="#3e3e3e" onChange={() => setPasswd(!passwd)} value={!passwd} /> <Text>{passwd ? "Mostrar Senha" : "Esconder Senha"}</Text> </View> <View style={styles.button_container}> <TouchableOpacity style={styles.button} onPress={() => { verificarLogin() }}> <Text>Login</Text> </TouchableOpacity> </View> <View style={styles.signup_container}> <TouchableOpacity onPress={() => { setModalVisible(!modalVisible), setErro(false), setEmail(''), setSenha('') }}><Text>Não tem login? Cadastre-se</Text></TouchableOpacity> </View> <View style={styles.button_container}> <TouchableOpacity style={styles.button} onPress={() => navigation.navigate('Home')}> <Text>Continuar sem Logar</Text> </TouchableOpacity> </View> </View> <Modal animationType="fade" visible={modalVisible} > <ScrollView style={styles.container}> <View style={styles.header}> <Text style={styles.text_header}>Faça seu Cadastro Aqui!</Text> </View> <View style={styles.footer}> <View style={styles.input_container}> <TextInput placeholder="Email" placeholderTextColor={erro1 ? 'red' : 'gray'} style={[styles.textInput, erro1 ? styles.actionError : styles.errorMsg]} onChangeText={email => { setEmail1(email), setErro1(false) }} value={email1 != '' ? email1 : ''} /> </View> <View style={styles.input_container}> <TextInput placeholder="Password" placeholderTextColor={erro1 ? 'red' : 'gray'} style={[styles.textInput, erro1 ? styles.actionError : styles.errorMsg]} secureTextEntry={passwd} onChangeText={senha => { setSenha0(senha), setErro1(false) }} value={senha0 != '' ? senha0 : ''} /> </View> <View style={styles.input_container}> <TextInput placeholder="Password" placeholderTextColor={erro1 ? 'red' : 'gray'} style={[styles.textInput, erro1 ? styles.actionError : styles.errorMsg]} secureTextEntry={passwd} onChangeText={senha => { setSenha1(senha), setErro1(false) }} value={senha1 != '' ? senha1 : ''} /> </View> <View style={styles.switch_container}> <Switch trackColor={{ false: "#767577", true: "#000" }} thumbColor={passwd ? "#fff" : "orange"} ios_backgroundColor="#3e3e3e" onChange={() => setPasswd(!passwd)} value={!passwd} /> <Text>{passwd ? "Mostrar Senhas" : "Esconder Senhas"}</Text> </View> <View style={styles.button_container}> <TouchableOpacity style={styles.button} onPress={() => salvarLogin()}> <Text>Cadastrar</Text> </TouchableOpacity> </View> <View style={styles.button_container}> <TouchableOpacity onPress={() => { setModalVisible(!modalVisible), setErro1(false), setEmail1(''), setSenha0(''), setSenha1('') }} style={styles.button}><Text>Cancelar</Text></TouchableOpacity> </View> </View> </ScrollView> </Modal> </View > ) } <file_sep>import React from 'react'; import { createStackNavigator } from '@react-navigation/stack'; import { CartStackNavigation } from '../navigation'; const Stack = createStackNavigator(); export const Rotas = () => { return ( <Stack.Navigator> <Stack.Screen name="Cart" component={CartStackNavigation} /> </Stack.Navigator> ) }<file_sep>import React from 'react'; import { SafeAreaView } from 'react-native'; import Calc from './pages/components/calculator'; const App = () => { return ( <SafeAreaView> <Calc /> </SafeAreaView> ) } export default App;
8495f68aa5af129af62d2abb32e24b964f958948
[ "JavaScript" ]
15
JavaScript
GustavoRF77/DesenvolvimentoMobile_Serratec
962664ab366ba3e7d09536cd3c7176a9ed27bedf
0d52afa7571e9edb4f29f5121011b76608542ef8
refs/heads/master
<repo_name>JackLuo0826/ReactVideoPlayer<file_sep>/README.md # ReduxVideoPlayer This is a simple YouTube player made with React.js. To run just navigate to project folder and type the following in windows cmd/powershell: > npm start Then open browser and enter url - localhost:8080 <file_sep>/src/index.js import _ from 'lodash'; import React, { Component } from 'react'; // Responsible for Step 1. import ReactDOM from 'react-dom'; // Responsible for Step 2. import YTSearch from 'youtube-api-search'; import SearchBar from './components/search_bar'; import VideoList from './components/video_list'; import VideoDetail from './components/video_detail'; const API_KEY = '<KEY>'; // Step 1. Create a new component that produce HTML. // 'const' is a ES6 syntax for constants class App extends Component { constructor(props) { super(props); this.state = { videos: [], selectedVideo: null }; this.videoSearch('surfboards'); } videoSearch(term) { YTSearch({key: API_KEY, term: term}, videos => { //this.setState({ videos }); this.setState({ videos: videos, selectedVideo: videos[0] }); }); } render() { const videoSearch = _.debounce((term) => { this.videoSearch(term) }, 300); return ( <div> <SearchBar onSearchTermChange={videoSearch} /> <VideoDetail video={this.state.selectedVideo} /> <VideoList onVideoSelect={selectedVideo => this.setState({selectedVideo})} videos={this.state.videos} /> </div> // return some JSX ); } } // Step 2. Put component's generated HTML in the DOM. // App class is automatically instantiated this way by React. ReactDOM.render(<App />, document.querySelector('.container'));
d17a5d2406a31b9dad6a3462af869309279305c2
[ "Markdown", "JavaScript" ]
2
Markdown
JackLuo0826/ReactVideoPlayer
87450b467eb22873c778e353e4efb96a32f2c788
347b6e4daae643db3a8f88436951411a22df4e6c
refs/heads/master
<repo_name>zhuiyv/GestureLock<file_sep>/src/com/android/view/MyCycle.java package com.android.view; public class MyCycle { private float r; // 半径长度 private int x; //简略坐标 private int y; //简略坐标 private int perSize; //坐标系数 private boolean onTouch; // false=未选中 public float getR() { return r; } public void setR(float r) { this.r = r; } public boolean isOnTouch() { return onTouch; } public void setOnTouch(boolean onTouch) { this.onTouch = onTouch; } public boolean isPointIn(int x, int y) { double distance = Math.sqrt((x - this.getOx()) * (x - this.getOx()) + (y - this.getOy()) * (y - this.getOy())); return distance < r; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public int getPerSize() { return perSize; } public void setPerSize(int perSize) { this.perSize = perSize; } //获取实际x坐标 public int getOx() { return perSize * (x * 2 + 1); } //获取实际y坐标 public int getOy() { return perSize * (y * 2 + 1); } // 第y行 第x列 的编号 public int getNum() { return (3 * this.y + this.x); } } <file_sep>/src/com/android/gesturelock/MainActivity.java package com.android.gesturelock; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.Toast; import com.android.view.GestureLockView; import com.android.view.GestureLockView.OnGestureFinishListener; import com.example.gesturelock.R; public class MainActivity extends Activity implements OnClickListener{ GestureLockView gv; Button btnChange; String pwd = null; @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnChange = (Button) findViewById(R.id.btnChangePwd); btnChange.setOnClickListener(this); SharedPreferences sp = this.getSharedPreferences("config", MODE_PRIVATE); gv = (GestureLockView) findViewById(R.id.gv); if(sp != null){ pwd = sp.getString("pwd", null); } gv.setOnGestureFinishListener(new OnGestureFinishListener() { @Override public void OnGestureFinish(boolean result) { if(pwd == null){ Toast.makeText(MainActivity.this, "未检测到密码,请先设置", Toast.LENGTH_SHORT).show(); return; } if(result){ Toast.makeText(MainActivity.this, "验证成功!", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(MainActivity.this, "验证失败!", Toast.LENGTH_SHORT).show(); } } @Override public void OnSettingFinish(String result) { // TODO Auto-generated method stub } }); } @Override protected void onResume() { SharedPreferences sp = this.getSharedPreferences("config", MODE_PRIVATE); gv = (GestureLockView) findViewById(R.id.gv); if(sp != null){ pwd = sp.getString("pwd", null); } gv.setKey(pwd); super.onResume(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnChangePwd: Intent intent = new Intent(this, ChangePwd.class); startActivity(intent); break; default: break; } } }
fe97da820802f838a7bf808a604848d9277789be
[ "Java" ]
2
Java
zhuiyv/GestureLock
1b27f6ebff89346dd0f3bf085b5c7e4e41c14631
b2326041ffe1e4efc72acde1191bc8cadeab03db
refs/heads/master
<file_sep>'use strict'; if (!WEBGL.isWebGLAvailable()) { document.body.appendChild(WEBGL.getWebGLErrorMessage()); } let renderer, camera, scene; let pointerLockControls, position; // let orbitControls; let clock = new THREE.Clock(); let dracoLoader = new THREE.DRACOLoader(); THREE.DRACOLoader.getDecoderModule(); THREE.DRACOLoader.setDecoderPath('.'); let stats = new Stats(); // stats let blocker = document.getElementById('blocker'); let instructions = document.getElementById('instructions'); instructions.style.display = 'none'; let pageWrapper = document.getElementById('page-wrapper'); pageWrapper.style.display = 'none'; let moveForward = false; let moveBackward = false; let moveLeft = false; let moveRight = false; let flyUp = false; let flyDown = false; // let canJump = false; let boost = false; let velocity = new THREE.Vector3(); let direction = new THREE.Vector3(); // direction of movements let rotation = new THREE.Vector3(); // current camera direction const speed = 500.0; // const upSpeed = 200.0; const eyeLevel = 10.0; const geometryScale = 10; const zoomFactor = 3; const boostFactor = 3; const pointSize = 3; const container = document.createElement('div'); document.body.appendChild(container); function initRender() { // camera camera = new THREE.PerspectiveCamera(50, window.innerWidth/window.innerHeight, 0.01, 2000); // scene scene = new THREE.Scene(); scene.background = new THREE.Color(0xffffff); // scene.fog = new THREE.Fog(0xeeeeff, 0, 2000); // axes helper // scene.add(new THREE.AxesHelper(100)); // control panel gui // createPanel(); // lights scene.add(new THREE.AmbientLight()); // addShadowedLight(0, 100, 10, 0xffffff, 1); // addShadowedLight(50, 100, -100, 0xeeeeee, 1); // renderer renderer = new THREE.WebGLRenderer({antialias: true}); renderer.setPixelRatio(window.devicePixelRatio); renderer.setSize(window.innerWidth, window.innerHeight); // renderer.setClearColor(scene.fog.color); container.appendChild(renderer.domElement); window.addEventListener('resize', onWindowResize, false); } // function createPanel() { // let panel = new dat.GUI({width: 300}); // let folder = panel.addFolder('Setting'); // settings = { // 'point size': pointSize, // 'zoom factor': 3, // 'boost factor': 3, // 'speed': 500, // 'geometry scale': 10 // }; // folder.add(settings, 'point size', 1, 30, 1).onChange( // (size) => {pointSize = size} // ); // } function initControls() { // orbitControls = new THREE.OrbitControls(camera, renderer.domElement); pointerLockControls = new THREE.PointerLockControls(camera); pointerLockControls.getObject().position.y = eyeLevel; pointerLockControls.getObject().position.z = eyeLevel; instructions.addEventListener('click', () => { pointerLockControls.lock(); }, false); pointerLockControls.addEventListener('lock', () => { instructions.style.display = 'none'; blocker.style.display = 'none'; // pageWrapper.style.display = 'none'; container.appendChild(stats.dom); }); pointerLockControls.addEventListener('unlock', () => { blocker.style.display = 'block'; instructions.style.display = ''; // pageWrapper.style.display = ''; container.removeChild(stats.dom); }); scene.add(pointerLockControls.getObject()); const onKeyDown = event => { switch (event.keyCode) { case 38: // up case 87: // w moveForward = true; break; case 37: // left case 65: // a moveLeft = true; break; case 40: // down case 83: // s moveBackward = true; break; case 39: // right case 68: // d moveRight = true; break; case 81: // q flyUp = true; break; case 69: // e flyDown = true; break; // case 32: // space // if (canJump == true) { // velocity.y += upSpeed; // } // canJump = false; // break; case 32: // space camera.zoom = zoomFactor; camera.updateProjectionMatrix(); break; case 16: // shift boost = true; break; } }; const onKeyUp = event => { switch (event.keyCode) { case 38: // up case 87: // w moveForward = false; break; case 37: // left case 65: // a moveLeft = false; break; case 40: // down case 83: // s moveBackward = false; break; case 39: // right case 68: // d moveRight = false; break; case 81: // q flyUp = false; break; case 69: // e flyDown = false; break; case 32: // space camera.zoom = 1; camera.updateProjectionMatrix(); break; case 16: // shift boost = false; break; } console.log( 'controls: ', pointerLockControls.getObject().position ); }; document.addEventListener('keydown', onKeyDown, false); document.addEventListener('keyup', onKeyUp, false); } function initModel() { // const floorGeometry = new THREE.PlaneBufferGeometry(10000, 10000, 100, 100); // floorGeometry.rotateX(-Math.PI/2); // // floorGeometry = floorGeometry.toNonIndexed(); // position = floorGeometry.attributes.position; // // const floorMaterial = new THREE.MeshBasicMaterial({ // vertexColors: THREE.VertexColors, // wireframe: true // }); // // const floor = new THREE.Mesh(floorGeometry, floorMaterial); // scene.add(floor); // floor.name = 'model'; // dracoLoader.setVerbosity(1); dracoLoader.load( 'globalShifted_pointCloud_for_viewing.drc', onDecode, function(xhr) { console.log((xhr.loaded/xhr.total*100) + '% loaded'); }, function(error) { console.log('An error happened'); alert('Loading Error'); } ); } function onDecode(bufferGeometry) { // const material = new THREE.MeshStandardMaterial({vertexColors: THREE.VertexColors}); const geometry = resizeGeometry(bufferGeometry); // const selectedObject = scene.getObjectByName('model'); // scene.remove(selectedObject); geometry.name = 'model'; scene.add(geometry); THREE.DRACOLoader.releaseDecoderModule(); instructions.style.display = ''; } function resizeGeometry(bufferGeometry) { let geometry, material; bufferGeometry.rotateX(-Math.PI/2); position = bufferGeometry.attributes.position; if (bufferGeometry.index) { bufferGeometry.computeVertexNormals(); material = new THREE.MeshStandardMaterial({vertexColors: THREE.VertexColors}); geometry = new THREE.Mesh(bufferGeometry, material); } else { // point cloud does not have face indices material = new THREE.PointsMaterial({ vertexColors: THREE.VertexColors, size: pointSize }); geometry = new THREE.Points(bufferGeometry, material); } // Compute range of the geometry coordinates for proper rendering. // bufferGeometry.computeBoundingBox(); bufferGeometry.center(); // const sizeX = bufferGeometry.boundingBox.max.x - bufferGeometry.boundingBox.min.x; // const sizeY = bufferGeometry.boundingBox.max.y - bufferGeometry.boundingBox.min.y; // const sizeZ = bufferGeometry.boundingBox.max.z - bufferGeometry.boundingBox.min.z; // const diagonalSize = Math.sqrt(sizeX*sizeX + sizeY*sizeY + sizeZ*sizeZ); // const scale = 1.0/diagonalSize; // const midX = (bufferGeometry.boundingBox.min.x + bufferGeometry.boundingBox.max.x)/2; // const midZ = (bufferGeometry.boundingBox.min.z + bufferGeometry.boundingBox.min.z)/2; // geometry.scale.multiplyScalar(scale); // geometry.position.x = -midX*scale; // geometry.position.y = -midY*scale; // geometry.position.z = -midZ*scale; // geometry.castShadow = true; // geometry.receiveShadow = true; geometry.scale.set(geometryScale, geometryScale, geometryScale); console.log( 'geometry position: ', geometry.position.x, geometry.position.y, geometry.position.z ); return geometry; } function init() { initRender(); initControls(); initModel(); } function animate() { requestAnimationFrame(animate); stats.update(); if (pointerLockControls.isLocked) { let control = pointerLockControls.getObject(); const delta = clock.getDelta(); velocity.x -= velocity.x*10.0*delta; velocity.z -= velocity.z*10.0*delta; velocity.y -= velocity.y*10.0*delta; // velocity.y -= 9.8*100.0*delta; // 100.0 = mass direction.z = Number(moveForward) - Number(moveBackward); direction.x = Number(moveLeft) - Number(moveRight); direction.y = Number(flyUp) - Number(flyDown); direction.normalize(); // this ensure consistent movements in all directions if (moveForward || moveBackward) { velocity.z -= direction.z*speed*delta*(1 + Number(boost)*boostFactor); } if (moveLeft || moveRight) { velocity.x -= direction.x*speed*delta*(1 + Number(boost)*boostFactor); } if (flyUp || flyDown) { velocity.y += direction.y*speed*delta*(1 + Number(boost)*boostFactor); } pointerLockControls.getObject().translateX(velocity.x*delta); pointerLockControls.getObject().translateZ(velocity.z*delta); pointerLockControls.getObject().translateY(velocity.y*delta); // if (pointerLockControls.getObject().position.y < eyeLevel) { // velocity.y = 0; // pointerLockControls.getObject().position.y = eyeLevel; // canJump = true; // } } renderer.render(scene, camera); } function onWindowResize() { camera.aspect = window.innerWidth/window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); } window.onload = () => { // const fileInput = document.getElementById('fileInput'); // fileInput.onclick = () => this.value = ''; // fileInput.addEventListener('change', e => { // const file = fileInput.files[0]; // const reader = new FileReader(); // reader.onload = e => { // // Enable logging to console output. // dracoLoader.setVerbosity(1); // dracoLoader.decodeDracoFile(reader.result, onDecode); // } // reader.readAsArrayBuffer(file); // }); init(); animate(); } <file_sep># react360tutorial - [Setting up Tools, and Creating Your First Project](https://facebook.github.io/react-360/docs/setup.html)
ccd86183e5e59616fca82a63a0d67b1420bc79d6
[ "JavaScript", "Markdown" ]
2
JavaScript
ngchanway/react360tutorial
f5ea0de61cd24fc2987500c51689618451f425a9
67c651c33d7564ec91d598f528d32de4d266c04e
refs/heads/master
<repo_name>LeoLeBras/experimental-molecular-graphql<file_sep>/shared/graphql-binding-customer/src/resolvers.ts import { GraphQLResolveInfo } from 'graphql' import { BillingBinding } from '@acme/graphql-binding-billing' import { Client } from './binding' interface Context { database: any bindings: { billing: BillingBinding } } export default { Query: { client: async (root, args: { id?: number }, ctx: Context): Promise<Client | null> => { return ctx.database.Client.findById(args.id) }, }, Client: { invoices: (root: Client, args, ctx: Context, info: GraphQLResolveInfo | string) => { return ctx.bindings.billing.query.invoices({ where: { clientId: root.id } }, info) }, }, } <file_sep>/apps/server-core-services/src/services/BillingService.ts import { createGraphQLService } from 'moleculer-graphql-binding' import { ServiceBroker } from 'moleculer' export default function BillingService(broker: ServiceBroker, bindings, database) { return createGraphQLService('billing', bindings, database)(broker) } <file_sep>/librairies/moleculer-graphql-binding/src/index.ts export { default as createGraphqlBrokerServices } from './createGraphqlBrokerServices' export { default as createGraphQLService } from './createGraphQLService' <file_sep>/apps/server-core-services/src/services/CustomerService.ts import { createGraphQLService } from 'moleculer-graphql-binding' import { ServiceBroker } from 'moleculer' export default function CustomerService(broker: ServiceBroker, bindings, database) { return createGraphQLService('customer', bindings, database)(broker) } <file_sep>/apps/server-core-services/src/bootstrap.ts import { ServiceBroker, Service } from 'moleculer' import { createGraphqlBrokerServices } from 'moleculer-graphql-binding' import { Binding } from 'graphql-binding' import services from './services' import bindings from './bindings' import database from './database' interface BootstrapResponse { broker: ServiceBroker bindings: { [name: string]: Binding } } export default async function bootstrap( resolve: (reponse: BootstrapResponse) => void, reject: (err: Error) => void, ) { try { // Initialize servicer broker const options = { metrics: true } const broker = new ServiceBroker(options) // Create GraphQL services const response = createGraphqlBrokerServices(services, bindings, database)(broker) // Start broker await broker.start() // Resolve response resolve(response) } catch (err) { // Reject error reject(err) } } <file_sep>/librairies/moleculer-graphql-binding/src/createBindingInstanceName.ts import { titleCase } from 'change-case' export default function createBindingInstanceName(name: string) { return `${titleCase(name)}Binding` } <file_sep>/README.md ###### 🚨 This is highly experimental, APIs will change, use it with maximum precautions. # experimental-moleculer-graphql 🥁 A simple way to use the new big thing from the GraphQL community: **GraphQL Binding** with the moleculer library. <file_sep>/shared/graphql-binding-billing/src/binding.ts import { makeBindingClass, Options } from 'graphql-binding' import { GraphQLResolveInfo, GraphQLSchema } from 'graphql' import { IResolvers } from 'graphql-tools/dist/Interfaces' import schema from './schema' export interface Query { invoices: <T = Invoice[] | null>(args: { where?: InvoiceWhereInput }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> } export interface Mutation { createInvoice: <T = Invoice | null>(args: { input?: InvoiceCreateInput }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> } export interface Subscription {} export interface Binding { query: Query mutation: Mutation subscription: Subscription request: <T = any>(query: string, variables?: {[key: string]: any}) => Promise<T> delegate(operation: 'query' | 'mutation', fieldName: string, args: { [key: string]: any; }, infoOrQuery?: GraphQLResolveInfo | string, options?: Options): Promise<any>; delegateSubscription(fieldName: string, args?: { [key: string]: any; }, infoOrQuery?: GraphQLResolveInfo | string, options?: Options): Promise<AsyncIterator<any>>; getAbstractResolvers(filterSchema?: GraphQLSchema | string): IResolvers; } export interface BindingConstructor<T> { new(...args): T } export const Binding = makeBindingClass<BindingConstructor<Binding>>({ schema }) /** * Types */ export type InvoiceStatus = 'unpaid' | 'paid' export interface InvoiceCreateInput { name?: String } export interface InvoiceWhereInput { clientId?: Int } export interface Client { id: Int firstName: String lastName: String invoices?: Invoice[] } export interface Invoice { id: Int name: String client?: Client clientId?: Int status: InvoiceStatus } /* The `Boolean` scalar type represents `true` or `false`. */ export type Boolean = boolean /* The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text. */ export type String = string /* The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1. */ export type Int = number<file_sep>/apps/server-core-services/src/database/InvoiceModel.ts export default class InvoiceModel { static findAllByClientId(clientId: string) { return Promise.resolve([ { id: 1, name: '00001', }, { id: 2, name: '00002', }, ]) } } <file_sep>/librairies/moleculer-graphql-binding/src/MoleculerLink.ts import { ServiceBroker } from 'moleculer' import { ApolloLink, Observable } from 'apollo-link' import { print } from 'graphql' interface Options { serviceName: string serviceBroker: ServiceBroker } function createMoleculerLink(options: Options) { return new ApolloLink( operation => new Observable(observer => { const { serviceBroker, serviceName } = options const { variables, query } = operation serviceBroker .call('customer.execute', { query: print(query), variables, serviceName }) .then(results => { observer.next(results) observer.complete() }) .catch(err => { observer.error(err) }) }), ) } export default class MoleculerLink extends ApolloLink { constructor(options: Options) { super(createMoleculerLink(options).request) } } <file_sep>/librairies/moleculer-graphql-binding/src/createContextBindings.ts import { Binding } from 'graphql-binding' import { ServiceBroker } from 'moleculer' import MoleculerLink from './MoleculerLink' import createBindingContextName from './createBindingContextName' export default function createContextBindings( bindingName: string, bindings: Binding[], broker: ServiceBroker, ) { return Object.keys(bindings).reduce((acc, key) => { if (key !== bindingName) { const name = createBindingContextName(key) const link = new MoleculerLink({ serviceName: name, serviceBroker: broker }) const binding = new bindings[key](link) return { ...acc, [name]: binding } } return acc }, {}) } <file_sep>/librairies/moleculer-graphql-binding/src/createGraphqlBrokerServices.ts import { forEach } from 'iterall' import { ServiceBroker } from 'moleculer' import { Binding } from 'graphql-binding' interface GraphQLBrokerServicesResponse { broker: ServiceBroker bindings: { [name: string]: Binding } } export default function createGraphqlBrokerServices(services, bindings, database) { return function(broker: ServiceBroker): GraphQLBrokerServicesResponse { let instantiatedBindings = {} forEach(Object.keys(services), (serviceName: string) => { const { name, actions, binding } = services[serviceName](broker, bindings, database) broker.createService({ name, actions }) instantiatedBindings[name] = binding }) return { broker, bindings: instantiatedBindings } } } <file_sep>/shared/graphql-binding-billing/src/resolvers.ts import { GraphQLResolveInfo } from 'graphql' import { CustomerBinding } from '@acme/graphql-binding-customer' import { Invoice, InvoiceCreateInput } from './binding' interface Context { database: any bindings: { customer: CustomerBinding } } export default { Query: { invoices: (root, args: { where?: { clientId?: number } }, ctx: Context) => { return ctx.database.Invoice.findAllByClientId(args) }, }, Mutation: { createInvoice: (args: { input: InvoiceCreateInput }) => { // return ctx.database.Invoice.create(args) return Promise.resolve(null) }, }, Invoice: { client: (root: Invoice, args, ctx: Context, info: GraphQLResolveInfo | string) => { return ctx.bindings.customer.query.client({ id: root.clientId }, info) }, }, } <file_sep>/apps/server-core-services/src/database/ClientModel.ts export default class ClientModel { static findById(id: string) { return Promise.resolve({ id, firstName: 'Léo', lastName: '<NAME>' }) } } <file_sep>/apps/server-core-services/src/services/index.ts export default { get BillingService() { return require('./BillingService').default }, get CustomerService() { return require('./CustomerService').default }, } <file_sep>/shared/graphql-types/src/index.ts import { importSchema } from 'graphql-import' export const Types = importSchema(`${__dirname}/types.graphql`) <file_sep>/apps/server-core-services/src/database/index.ts export default { get Client() { return require('./ClientModel').default }, get Invoice() { return require('./InvoiceModel').default }, } <file_sep>/apps/server-core-services/src/bindings/index.ts export default { get CustomerBinding() { return require('@acme/graphql-binding-customer').CustomerBinding }, get BillingBinding() { return require('@acme/graphql-binding-billing').BillingBinding }, } <file_sep>/shared/graphql-binding-customer/src/index.ts import { makeRemoteExecutableSchema } from 'graphql-tools' import { Binding } from './binding' import schema from './schema' class CustomerBinding extends Binding { constructor(link) { super({ schema: link ? makeRemoteExecutableSchema({ schema, link }) : schema }) } } export { CustomerBinding } <file_sep>/librairies/moleculer-graphql-binding/src/createBindingContextName.ts import { ServiceBroker } from 'moleculer' import { lowerCase } from 'change-case' export default function createBindingInstanceName(name: string) { return `${lowerCase(name.slice(0, -7))}` } <file_sep>/shared/graphql-binding-billing/src/schema.ts import { makeExecutableSchema } from 'graphql-tools' import { importSchema } from 'graphql-import' import { Types } from '@acme/graphql-types' import resolvers from './resolvers' export const typeDefs = importSchema(` ${Types} # import Query from "${__dirname}/queries.graphql" # import Mutation from "${__dirname}/mutations.graphql" # import Input from "${__dirname}/inputs.graphql" `) export default makeExecutableSchema({ typeDefs, resolvers, }) <file_sep>/shared/graphql-binding-customer/src/binding.ts import { makeBindingClass, Options } from 'graphql-binding' import { GraphQLResolveInfo, GraphQLSchema } from 'graphql' import { IResolvers } from 'graphql-tools/dist/Interfaces' import schema from './schema' export interface Query { client: <T = Client | null>(args: { id?: Int }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> } export interface Mutation {} export interface Subscription {} export interface Binding { query: Query mutation: Mutation subscription: Subscription request: <T = any>(query: string, variables?: {[key: string]: any}) => Promise<T> delegate(operation: 'query' | 'mutation', fieldName: string, args: { [key: string]: any; }, infoOrQuery?: GraphQLResolveInfo | string, options?: Options): Promise<any>; delegateSubscription(fieldName: string, args?: { [key: string]: any; }, infoOrQuery?: GraphQLResolveInfo | string, options?: Options): Promise<AsyncIterator<any>>; getAbstractResolvers(filterSchema?: GraphQLSchema | string): IResolvers; } export interface BindingConstructor<T> { new(...args): T } export const Binding = makeBindingClass<BindingConstructor<Binding>>({ schema }) /** * Types */ export interface Invoice { id: Int name?: String client?: Client clientId?: Int } export interface Client { id: Int firstName?: String lastName?: String invoices?: Invoice[] } /* The `Boolean` scalar type represents `true` or `false`. */ export type Boolean = boolean /* The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text. */ export type String = string /* The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1. */ export type Int = number<file_sep>/librairies/moleculer-graphql-binding/src/createActions.ts import { Context } from 'moleculer' import { Binding } from 'graphql-binding' import { execute, parse } from 'graphql' import createBindingInstanceName from './createBindingInstanceName' export default function createAction(binding: Binding, bindings, context) { return Object.keys(binding.query).reduce( (acc, operationName) => ({ ...acc, [`query.${operationName}`]: (ctx: Context) => { return new Promise(async (resolve, reject) => { try { const { variables, fragment } = ctx.params const options = { context } const response = await binding.delegate( 'query', operationName, variables, fragment, options, ) resolve(response) } catch (err) { reject(err) } }) }, execute: { params: { serviceName: 'string', query: 'string', variables: 'object' }, handler(ctx: Context) { return new Promise(async (resolve, reject) => { try { const { serviceName, query, variables } = ctx.params const scopedBinding = new bindings[(createBindingInstanceName(serviceName))]() const response = await execute( scopedBinding.schema, parse(query), undefined, context, variables, ) resolve(response) } catch (err) { reject(err) } }) }, }, }), {}, ) } <file_sep>/librairies/moleculer-graphql-binding/src/createGraphQLService.ts import { ServiceBroker } from 'moleculer' import MoleculerLink from './MoleculerLink' import createBindingInstanceName from './createBindingInstanceName' import createContextBindings from './createContextBindings' import createActions from './createActions' export default function createGraphQLService(name: string, bindings, database) { return function(broker: ServiceBroker) { const bindingName = createBindingInstanceName(name) const binding = new bindings[bindingName]() const contextBindings = createContextBindings(bindingName, bindings, broker) const context = { bindings: contextBindings, database } const actions = createActions(binding, bindings, context) const link = new MoleculerLink({ serviceName: name, serviceBroker: broker }) return { name, actions, binding: new bindings[bindingName](link) } } } <file_sep>/apps/server-core-services/src/index.ts import bootstrap from './bootstrap' bootstrap( async ({ broker, bindings: { customer } }) => { console.log(`🎊 Server started`) // First call with simple broker call const firstResponse = await broker.call('customer.query.client', { variables: { id: 2 }, }) console.log('➡️ ', firstResponse) // Second call via broker with fragment const secondResponse = await broker.call('customer.query.client', { variables: { id: 2 }, fragment: 'fragment client on Client { id, firstName, lastName, invoices { id } }', }) console.log('➡️ ', secondResponse) // Thrid call via binding const thridResponse = await customer.query.client({ id: 2 }) console.log('➡️ ', thridResponse) }, err => { console.log(`😡 Something went wrong ${err}`) }, ) <file_sep>/shared/graphql-binding-customer/src/schema.ts import { makeExecutableSchema } from 'graphql-tools' import { importSchema } from 'graphql-import' import { Types } from '@acme/graphql-types' import resolvers from './resolvers' export const typeDefs = importSchema(` ${Types} # import Query.* from "${__dirname}/queries.graphql" `) export default makeExecutableSchema({ typeDefs, resolvers, })
b439c6a3a26df7b8e82007fd6f5d51561dba86d1
[ "Markdown", "TypeScript" ]
26
TypeScript
LeoLeBras/experimental-molecular-graphql
2f0de0025656c121ba101ab5bd817ea8f2586cd6
1f35f19d17d03afe7263f61dfd30747da61d67ba
refs/heads/master
<file_sep>import { inject, InjectionKey, provide } from '@vue/composition-api'; import { VueRouter } from 'vue-router/types/router'; const RouterKey: InjectionKey<VueRouter> = Symbol(); export function provideRouter(router: VueRouter) { provide(RouterKey, router); } export function useRouter(): VueRouter { return inject(RouterKey) as VueRouter; } <file_sep>import { IRootState } from '@/interfaces/store.interfaces'; const initialState: IRootState = { username: 'random#1', difficulty: 2, ranking: [], score: 0, lives: 3, isPaused: false, }; export default initialState; <file_sep>import Vue from 'vue'; import App from './App.vue'; import router from './router'; import store from './store/store'; import VueCompositionApi from '@vue/composition-api'; import locale from 'element-ui/lib/locale'; import lang from 'element-ui/lib/locale/lang/en'; locale.use(lang); Vue.use(VueCompositionApi); Vue.config.productionTip = false; new Vue({ router, store, render: (h) => h(App), }).$mount('#app'); <file_sep>declare module '*.vue' { import Vue from 'vue'; export default Vue; } declare module 'element-ui/lib/dialog.js'; declare module 'element-ui/lib/input.js'; declare module 'element-ui/lib/dropdown.js'; declare module 'element-ui/lib/dropdown-menu.js'; declare module 'element-ui/lib/dropdown-item.js'; declare module 'element-ui/lib/tree.js'; declare module 'element-ui/lib/table.js'; declare module 'element-ui/lib/table-column.js'; declare module 'element-ui/lib/breadcrumb.js'; declare module 'element-ui/lib/breadcrumb-item.js'; declare module 'element-ui/lib/button.js'; declare module 'element-ui/lib/switch.js'; declare module 'element-ui/lib/radio.js'; declare module 'element-ui/lib/radio-group.js'; declare module 'element-ui/lib/upload.js'; declare module 'element-ui/lib/pagination.js'; declare module 'element-ui/lib/form.js'; declare module 'element-ui/lib/form-item.js'; declare module 'element-ui/lib/modal.js'; declare module 'element-ui/lib/option.js'; declare module 'element-ui/lib/select.js'; declare module 'element-ui/lib/tag.js'; declare module 'element-ui/lib/collapse.js'; declare module 'element-ui/lib/collapse-item.js'; declare module 'element-ui/lib/notification.js'; declare module 'element-ui/lib/date-picker.js'; declare module 'element-ui/lib/table-column.js'; declare module 'element-ui/lib/locale/lang/en'; declare module 'element-ui/lib/locale'; <file_sep>import Vue from 'vue'; import VueRouter from 'vue-router'; Vue.use(VueRouter); const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes: [ { path: '/menu', name: 'Menu', component: () => import(/* webpackChunkName: "reflex" */ '@/views/Menu.view.vue'), }, { path: '/game', name: 'Game', component: () => import(/* webpackChunkName: "reflex" */ '@/views/Game.view.vue'), }, { path: '**', redirect: '/menu', }, ], }); export default router; <file_sep>import Vue from 'vue'; import Vuex, { StoreOptions } from 'vuex'; import initialState from './state'; import { IRootState } from '@/interfaces/store.interfaces'; Vue.use(Vuex); export default new Vuex.Store<IRootState>({ state: { ...initialState }, mutations: { RESET_STATE(state) { state = Object.assign(state, initialState); }, SET_IS_PAUSED(state, payload) { state.isPaused = payload; }, DECREASE_LIVES(state) { state.lives--; }, SET_USERNAME(state, value) { state.username = value; }, SET_DIFFICULTY(state, value) { state.difficulty = value; }, INCREASE_SCORE(state) { state.score++; }, }, } as StoreOptions<IRootState>); <file_sep>import { inject, InjectionKey, provide } from '@vue/composition-api'; import { IRootState } from '@/interfaces/store.interfaces'; import { Store } from 'vuex'; const StoreKey: InjectionKey<Store<IRootState>> = Symbol(); export function provideStore(store: Store<IRootState>) { provide(StoreKey, store); } export function useStore() { const store = inject(StoreKey); if (!store) { throw new Error('NO STORE PROVIDED'); } return store; } <file_sep>export interface IRootState { score: number; username: string; difficulty: number; ranking: IRankingRecord[]; lives: number; isPaused: boolean; } export interface IRankingRecord { username: string; score: number; date: Date; }
8fe5a58d833eb3b81f68036641105d8162482cd7
[ "TypeScript" ]
8
TypeScript
adamJacewicz/vue3-reflex
397d4f59a83b91bfaa06f788d97151bce122ae05
99ef4672de4a0790e937dd0428689bea9a0937da
refs/heads/master
<file_sep>int color(int a) { switch(a) { case 1:return 37; case 3:return 31; case 2:return 36; case 5:return 32; case 8:return 33; case 13:return 34; case 21:return 35; case 34:return 36; case 55:return 35; case 89:return 33; case 144:return 37; case 233:return 31; case 377:return 32; case 610:return 33; case 987:return 34; case 1597:return 35; case 2584:return 36; case 4181:return 37; case 6765:return 31; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <time.h> #include "lib.h" #define SIZE 4 int score=0; int arr[]={1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765}; int search(int a,int b) { int i; if(a==1&&b==1) return 1; else { for(i=0;i<17;i++) if(arr[i]==a) break; return(arr[i+1]==b||arr[i-1]==b); } } void display(int board[SIZE][SIZE],int m) { printf("\033[2J"); printf("\n\n\n\n\n\n\n\n\n BEST SCORE:%d\n YOUR SCORE:%d\n\n",m,score); for(int i=0;i<SIZE;i++) {printf(" "); for(int j=0;j<SIZE;j++) { if(board[i][j]==0) printf(". "); else { printf("\033[%dm",color(board[i][j])); if(board[i][j]<10) printf("%d ",board[i][j]); else printf("%d ",board[i][j]); printf("\033[37m"); } } printf("\n\n"); } } int find(int array[SIZE],int x,int stop) { int t; if (x==0) { return x; } for(t=x-1;t>=0;t--) { if (array[t]!=0) { if(search(array[t],array[x])) { return t; } return t+1; } else { if (t==stop) { return t; } } } return x; } bool movearray(int array[SIZE]) { bool success = false; int x,t,stop=0; for (x=0;x<SIZE;x++) { if (array[x]!=0) { t = find(array,x,stop); if (t!=x) { if (array[t]==0) { array[t]=array[x]; } else if (search(array[t],array[x])) { array[t]=array[t]+array[x]; score+=array[t]; stop = t+1; } array[x]=0; success = true; } } } return success; } void rotate(int board[SIZE][SIZE]) { int i,j,n=SIZE; int tmp; for (i=0; i<n/2; i++) { for (j=i; j<n-i-1; j++) { tmp = board[i][j]; board[i][j] = board[j][n-i-1]; board[j][n-i-1] = board[n-i-1][n-j-1]; board[n-i-1][n-j-1] = board[n-j-1][i]; board[n-j-1][i] = tmp; } } } bool moveleft(int board[SIZE][SIZE]) { bool success = false; int x; for (x=0;x<SIZE;x++) { success=success|movearray(board[x]); } return success; } bool moveup(int board[SIZE][SIZE]) { bool success; rotate(board); success = moveleft(board); rotate(board); rotate(board); rotate(board); return success; } bool moveright(int board[SIZE][SIZE]) { bool success; rotate(board); rotate(board); success = moveleft(board); rotate(board); rotate(board); return success; } bool movedown(int board[SIZE][SIZE]) { bool success; rotate(board); rotate(board); rotate(board); success = moveleft(board); rotate(board); return success; } void addrandom(int board[SIZE][SIZE]) { int x,y; srand(time(NULL)); do { x=rand()%4; y=rand()%4; } while(board[x][y]); board[x][y]=1; } void create(int board[SIZE][SIZE]) { score=0; int x,y; for (x=0;x<SIZE;x++) { for (y=0;y<SIZE;y++) { board[x][y]=0; } } addrandom(board); // display(board,m); score = 0; } bool findpair(int board[SIZE][SIZE]) { bool success = false; int x,y; for (x=0;x<SIZE;x++) { for (y=0;y<SIZE-1;y++) { if (search(board[x][y],board[x][y+1])) return true; } } return success; } int countempty(int board[SIZE][SIZE]) { int x,y; int count=0; for (x=0;x<SIZE;x++) { for (y=0;y<SIZE;y++) { if (board[x][y]==0) { count++; } } } return count; } bool gameover(int board[SIZE][SIZE]) { bool ended = true; if (countempty(board)>0) return false; if (findpair(board)) return false; rotate(board); if (findpair(board)) ended = false; rotate(board); rotate(board); rotate(board); return ended; } int main() { int board[SIZE][SIZE]; char c,n; int m,k; bool success; FILE *hs; hs=fopen("highscore.txt","r+"); fscanf(hs,"%d",&m); printf("\033[2J"); printf("\033[?25l"); printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n i-instructions\n any other key to play\n\n\n"); scanf("%c",&c); if(c=='i') { printf("\033[2J"); printf("\n*fibinnocci series(sum of previous two numbers):1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584...\nnumbers can be added only when they are in series\n*while playing game:\n -use a,s,w,d to move\n -q to exit\n -i for information\n -r to restart"); printf("\n\nenter any key to continue:"); scanf(" %c",&n); } create(board); display(board,m); while (true) { scanf(" %c",&c); switch(c) { case 'a': case 'A':success = moveleft(board); break; case 'd': case 'D':success = moveright(board); break; case 'w': case 'W':success = moveup(board); break; case 's': case 'S':success = movedown(board); break; default: success = false; } if (success) { addrandom(board); display(board,m); if (gameover(board)) { break; } } if(c=='i'||c=='I') printf("\n*fibinnocci series(sum of previous two numbers):1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584...\nnumbers can be added only when they are in series\n*while playing game:\n -use a,s,w,d to move\n -q to exit\n -i for information\n -r to restart\n"); if (c=='q' || c=='Q') { printf(" QUIT? (y/n) \n"); scanf(" %c",&c); if (c=='y'||c=='Y') { break; } display(board,m); } if (c=='r'||c=='R') { printf(" RESTART? (y/n) \n"); scanf(" %c",&c); if (c=='y'||c=='Y') { create(board); display(board,m); } } } if(m<=score) { rewind(hs); fprintf(hs,"%d",score); m=score; } printf("\033[2J"); printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n GAME OVER\n YOUR SCORE:%d\n BEST SCORE:%d \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",score,m); return 0; }
f4aeeb415a7373771a531808bf56aa8dc4d49433
[ "C" ]
2
C
MADHURIbaradi/fibonacci-2048
08b29334196f1c4eac38d322c6e60e638a0c6033
922a3a3c1686456db04ee9fe81963f67ffcf0be0
refs/heads/master
<file_sep><?php namespace App\Controller; class FooController { }
22bb2a35b8005a5f993b08fac76174b476826a42
[ "PHP" ]
1
PHP
maximebarlet/mutli_container_sf
6ab8e837107fa903b208d640e4acd83e7bc16152
ae7794a8e4d5bddce891668c79ed668488beb7ec
refs/heads/master
<repo_name>pkindalov/JavaProgrammingBasic<file_sep>/AdvancedLoops/BinarySort_Quick.java import java.util.Arrays; public class BinarySort_Quick { // Quick Approach public static void binarySort_Quick(int[] arr) { // Set pivot to 1 int pivot = 1; int j = 0; // Each time a 0 is encountered, we increment j // 0 is placed before the pivot for (int i = 0; i < arr.length; i++) { if (arr[i] < pivot) { swap(arr,i,j); j++; } } System.out.println(Arrays.toString(arr)); } // Utility function to swap 2 elements in an array private static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } public static void main(String[] args) { int[] arr = {1, 0, 1, 0, 1, 0, 1, 1, 0, 0}; binarySort_Quick(arr); } } <file_sep>/ExamPrepProgrammBasicsExam28August2016/HotelRoom.java package ExamPrepProgrammBasicsExam28August2016; import java.util.Scanner; /** * Created by r3v3nan7 on 12.01.17. */ public class HotelRoom { public static void main(String[] args){ Scanner console = new Scanner(System.in); String month = console.nextLine().toLowerCase(); int nights = Integer.parseInt(console.nextLine()); double studioPrice = 0; double studioReduction = 0; double apartmentPrice = 0; double apartmenReduction = 0; double totalPriceStudio = 0; double totalPriceApartment = 0; switch (month){ case "may": case "october": studioPrice = 50; apartmentPrice = 65; if(nights > 7 && nights <= 14){ studioReduction = 0.05; }else if (nights > 14){ studioReduction = 0.3; apartmenReduction = 0.1; } break; case "june": case "september": studioPrice = 75.20; apartmentPrice = 68.70; if(nights > 14){ studioReduction = 0.2; apartmenReduction = 0.1; } break; case "july": case "august": studioPrice = 76; apartmentPrice = 77; if(nights > 14){ apartmenReduction = 0.1; } break; } totalPriceStudio = (studioPrice - (studioReduction * studioPrice)) * nights; totalPriceApartment = (apartmentPrice - (apartmenReduction * apartmentPrice)) * nights; System.out.printf("Apartment: %.2f lv.%n", totalPriceApartment); System.out.printf("Studio: %.2f lv.%n", totalPriceStudio); } } <file_sep>/AdvancedLoops/BinarySort_Comparison.java import java.util.Arrays; public class BinarySort_Comparison { // Comparison Approach public static void binarySort_Compare(int[] arr) { // Store the index of next available free index int k = 0; // Compare every element to 0 and if it matches, fill the next available index with a 0. for (int value : arr) { if (value == 0) { arr[k++] = 0; } } // Fill the rest of the array with 1's for (int i = k; i < arr.length; i++) { arr[i] = 1; } System.out.println(Arrays.toString(arr)); } public static void main(String[] args) { int[] arr = {1, 0, 1, 0, 1, 0, 1, 1, 0, 0}; binarySort_Compare(arr); } } <file_sep>/ExamPrepProgrammBasicsExam28August2016/Axe.java package ExamPrepProgrammBasicsExam28August2016; import java.util.Scanner; /** * Created by r3v3nan7 on 16.01.17. */ public class Axe { public static void main(String[] args){ Scanner console = new Scanner(System.in); int n = Integer.parseInt(console.nextLine()); int totalSymbolsPerRow = n * 5; int leftPartDots = n * 3; int rightPartDots = totalSymbolsPerRow - leftPartDots - 2; int middleDots = 0; int middleStars = 2; int currentRightDots = 0; int currentMiddleDots = 0; int handleOfAxe = n / 2; int rowsAfterHandleBeforLastRow = (n / 2) - 1; int leftDotsFinalRow = leftPartDots - rowsAfterHandleBeforLastRow; int starsFinalRow = totalSymbolsPerRow - leftDotsFinalRow; //drawing first n rows of axe or first part of draw for (int i = 0; i < n ; i++) { System.out.print(repeat("-", leftPartDots)); System.out.printf("*" + repeat("-", middleDots) + "*"); System.out.printf(repeat("-", rightPartDots)); System.out.println(); currentMiddleDots = middleDots; middleDots++; currentRightDots = rightPartDots; rightPartDots--; } //now drawing handle of axe for (int i = 0; i < handleOfAxe ; i++) { System.out.printf(repeat("*", leftPartDots) + "*"); System.out.printf(repeat("-", currentMiddleDots) + "*"); System.out.printf(repeat("-", currentRightDots)); System.out.println(); } //now drawing rows between hangle and last row.. for (int i = 0; i < rowsAfterHandleBeforLastRow ; i++) { System.out.printf(repeat("-", leftPartDots) + "*"); System.out.printf(repeat("-", currentMiddleDots) + "*"); System.out.printf(repeat("-", currentRightDots)); System.out.println(); leftPartDots--; currentRightDots--; currentMiddleDots += 2; } //now drawing final row int stars = starsFinalRow - currentRightDots; System.out.print(repeat("-", leftDotsFinalRow)); System.out.printf(repeat("*", stars)); System.out.printf(repeat("-", currentRightDots)); System.out.println(); } public static String repeat(String str, int count){ StringBuilder newStr = new StringBuilder(); for (int i = 0; i < count ; i++) { newStr.append(str); } return newStr.toString(); } } <file_sep>/ExamPrepProgrammBasicsExam28August2016/Hospital.java package ExamPrepProgrammBasicsExam28August2016; import java.util.Scanner; /** * Created by r3v3nan7 on 12.01.17. */ public class Hospital { public static void main(String[] args){ Scanner console = new Scanner(System.in); int days = Integer.parseInt(console.nextLine()); int doctors = 7; int treatedPatients = 0; int untreatedPatients = 0; for (int i = 1; i <= days ; i++) { int patients = Integer.parseInt(console.nextLine()); if(i % 3 == 0){ if(treatedPatients < untreatedPatients) doctors++; } if(doctors == patients){ treatedPatients += patients; }else if(doctors > patients){ treatedPatients += patients; }else { untreatedPatients += patients - doctors; treatedPatients += doctors; } } System.out.println("Treated patients: " + treatedPatients + "."); System.out.println("Untreated patients: " + untreatedPatients + "."); } } <file_sep>/README.md # JavaProgrammingBasic Exercises from Java Basic Course
89b22fbdb227c49d36f5be04230f2029ae76b767
[ "Markdown", "Java" ]
6
Java
pkindalov/JavaProgrammingBasic
d834faa23eb5d664e750bab45313a2d044e8ce53
1405419ad80bba1bf813d00477848b802e38c0a0
refs/heads/main
<repo_name>SarahZarei/Car-Detection<file_sep>/car detection.py import cv2 cap = cv2.VideoCapture('video.avi') car_cascade = cv2.CascadeClassifier('cars.xml') #width = cap.get(3) # float width #height = cap.get(4) # float height # Make a video writer to see if video being taken as input inflict any changes you make #fourcc = cv2.VideoWriter_fourcc(*"MJPG") #out_video = cv2.VideoWriter('result/output.avi', fourcc, 20.0, (int(width), int(height)), True) # Then try this while(cap.isOpened()): # Read each frame where ret is a return boollean value(True or False) ret, frame = cap.read() # if return is true continue because if it isn't then frame is of NoneType in that case you cant work on that frame if ret: # Any preprocessing you want to make on the frame goes here gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # See if preprocessing is working on the frame it should cars = car_cascade.detectMultiScale(gray, 1.1, 1) for (x, y, w, h) in cars: cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 0, 255), 2) cv2.imshow('frame', frame) # finally write your preprocessed frame into your output video #out_video.write(gray) # write the modifies frame into output video # to forcefully stop the running loop and break out, if it doesnt work use ctlr+c if cv2.waitKey(1) & 0xFF == ord('q'): break # break out if frame has return NoneType this means that once script encounters such frame it breaks out # You will get the error otherwise else: break #while True: # ret, frame = cap.read() # gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) # cars = car_cascade.detectMultiScale(gray, 1.1, 1) # for (x, y, w, h) in cars: # cv.rectangle(frame, (x, y), (x+w, y+h), (0, 0, 255), 2) #cv.imshow('video2', frame) #if cv.waitKey(33) == 27: # pass cv2.destroyAllWindows()<file_sep>/README.md # Car-Detection OpenCV Python program for Vehicle detection
f750a59588ca448ac562cdce66a7cf979cd209db
[ "Markdown", "Python" ]
2
Python
SarahZarei/Car-Detection
8366ae7b489cf8b58a56c5dc18a4eb30410a6947
7dc2552c31706a1338ccdcc1e3e2c2dd41ac9e49
refs/heads/master
<file_sep><?php require_once '../classes/PHPExcel.php'; // excel reader and destination file name $filetype = 'Excel2007'; $filename = 'Data.xlsx'; // Save csv file to xlsx format $objReader = PHPExcel_IOFactory::createReader('CSV'); $objPHPExcel = $objReader->load('data/testdata.csv'); $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $filetype); $objWriter->save($filename); // Read the xlsx file $objReader = PHPExcel_IOFactory::createReader($filetype); $objPHPExcel = $objReader->load($filename); // Add meta information to the xlsx file $objPHPExcel->getProperties() ->setCreator('') ->setTitle('') ->setLastModifiedBy('') ->setDescription('') ->setSubject('') ->setKeywords('') ->setCategory(''); function calcPercentage(){ // variables containing cell information (for percentage calculations) $column = 'I'; $row = 2; $colA = 'G'; $rowB = 2; $colB = 'H'; $rowB = 2; // Column I heading $objPHPExcel->setActiveSheetIndex(0) ->setCellValue('I1', 'PercentageScore'); // loop to apply the formula calculating percentage score for ($column = 'I'; $row < 102; $row++) { $objPHPExcel->getActiveSheet() ->setCellValue($column.$row, "=((" . $colA.$rowA . "/" . $colB.$rowB . ") * 100)"); $rowA++; $rowB++; } } calcPercentage(); // Save the xlsx file $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $filetype); $objWriter->save($filename); <file_sep><!DOCTYPE html> <html lang="en"> <head> <Title>PHPReport - Generate Client Summary Reports</Title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script src="http://code.highcharts.com/highcharts.js"></script> <!-- Bootstrap CDN --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script> <script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"> <link rel="stylesheet" href="css/style.css"> </head> <body> <div class="container"> <div class="row clearfix"> <div class="col-md-12 column"> <nav class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="http://www.fastbolt.com" target="blank"> <img style="max-width:100px; margin-top: -7px;" src="img/logo.png"> </a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li><a href="mailto:"><i class="fa fa-download"></i> Export XLSX</a></li> <li><a href="https://fbonline.fastbolt.com"><i class="fa fa-envelope"></i> Email</a></li> <li><a href="tel:+4401908650100"><i class="fa fa-file-pdf-o"></i> PDF</a></li> <li><a href="/phpreport/support" target="_blank"><i class="fa fa-question-circle"></i> Support</a></li> </ul> </div> </nav> </div> </div> </div> <section id="company"> <div class="container"> <div class="row clearfix"> <div class="col-md-4 column"> <img src="http://placehold.it/350x150"> </div> <div class="col-md-8 column"> <p>In sit amet hendrerit leo. Donec ac ex maximus, lacinia ligula interdum, lacinia elit. Duis mi metus, faucibus vitae posuere eget, hendrerit non nisi. Sed quis lacus vel magna ornare bibendum quis eget erat. Suspendisse aliquam, justo eu tempor maximus, enim purus rhoncus augue, sit amet volutpat nisl lectus et magna. Integer enim mauris, fermentum eget neque at, dapibus pulvinar libero. Maecenas sed volutpat erat. Nam vitae urna hendrerit, lacinia turpis a, consequat magna. Praesent sapien tellus, aliquet a nisi id, tincidunt viverra est. Curabitur commodo ipsum vel lorem pretium semper. Pellentesque efficitur, nulla nec luctus maximus, neque lorem pulvinar orci, at iaculis nisl turpis ut arcu. Sed non ultrices ante, eu rhoncus sapien. Pellentesque at diam justo. Sed tempor et leo ut elementum. Maecenas bibendum nulla orci, in rhoncus nibh placerat at. Aliquam sit amet orci eget tellus commodo accumsan et vitae tortor. Phasellus ac sapien a justo dictum mollis.</p> </div> </div> </div> </section> <section id="area"> <div class="container-fluid"> <div class="row clearfix"> <div class="col-md-12 column"> <h3>Collapsible items - configurable</h3> </div> </div> <div class="row clearfix"> <div class="col-md-6 col-lg-6"> <div class="panel panel-default" id="panel3"> <div class="panel-heading"> <h4 class="panel-title"> <a data-toggle="collapse" data-target="#collapseOne" href="#collapseOne" class="collapsed"> Area A Loc A Highest Scores <i class="fa fa-angle-double-down"></i> </a> </h4> </div> <div id="collapseOne" class="panel-collapse collapse"> <div class="panel-body"> <?php include 'area-graph.php'; ?> <div id="graph-container"></div> </div> </div> </div> </div> <!-- <div class="col-md-6 col-lg-6"> <div class="panel panel-default" id="panel3"> <div class="panel-heading"> <h4 class="panel-title"> <a data-toggle="collapse" data-target="#collapseThree" href="#collapseThree" class="collapsed"> Area A Loc A Highest Scores <i class="fa fa-angle-double-down"></i> </a> </h4> </div> <div id="collapseThree" class="panel-collapse collapse"> <div class="panel-body"> <?php include 'line-graph.php'; ?> <div id="line-container"></div> </div> </div> </div> </div> </div> </div> </section> <section id="location"> <div class="row clearfix"> <div class="col-md-12 column"> <h3>Real Time: <?php echo date("Y-m-d H:i:s");?> </h3> </div> </div> </section> <section id="area"> <div class="container"> <div class="row clearfix"> <div class="col-md-4"><?php include 'pie-graph.php'; ?><div id="pie-container"></div></div> <div class="col-md-4"><?php include 'pie-graph3.php'; ?><div id="pie-container3"></div></div> <div class="col-md-4"><?php include 'pie-graph4.php'; ?><div id="pie-container4"></div></div> </div> </div> </section> <section id="location"> <div class="row clearfix"> <div class="col-md-12 column"> <h3>Zooming enabled - configurable scales</h3> </div> </div> <div class="row clearfix"> <div class="row clearfix"> <div class="col-md-12"><?php include 'time-graph.php'; ?><div id="time-container"></div></div> </div> </div> </section> <section id="area"> <div class="container"> <div class="row clearfix"> <div class="col-md-12 column"> <h3>Another Title Here </h3> </div> </div> <div class="row clearfix"> <div class="col-md-6 column"> <form id="contact_form" method="post" action="contact.php" > <label>Name</label> <input name="name" placeholder="<NAME>"> <label>Company Name</label> <input name="company" placeholder="Company Name"> <label>Email</label> <input name="email" type="email" placeholder="Email Address"> <label>Enquiry</label> <textarea name="message" placeholder="Enquiry"></textarea> <input class="submit" name="submit" type="submit" value="submit"> </form> </div> </div> </div> </section> <section id="footer"> <div class="row clearfix"> <div class="col-md-12 column"> <img src="img/logo.png" height="100"> </div> </div> </section> --> </body> </html><file_sep><?php require_once 'includes/createtables.php'; class createGraphs extends uploadData{ public function areaQuery(){ $sql = "SELECT * FROM area_a WHERE LocName = 'Loc A';"; $result = $dbh->query($sql); while($row = $result->fetch(PDO::FETCH_BOTH)) { $score[] = $row['PointsScored']; $max[] = $row['PointsOutOf']; } } } ?> <script> $(function () { $('#graph-container').highcharts({ chart: { type: 'bar', backgroundColor:'rgba(255, 255, 255, 0.1)' }, title: { text: 'Area A Loc A Highest Scores' }, credits: { enabled: false }, xAxis: { categories: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] }, yAxis: { title: { text: 'Points Scored' } }, series: [{ name: 'Points Scored', data: [<?php echo implode($score, ',') ?>] }, { name: 'Points Out of', data: [<?php echo implode($max, ',') ?>] }] }); }); </script><file_sep><?php require_once 'upload-csv.php'; class createTablesMySQL extends uploadData{ public function breakDown(){ // Create tables to break down data $sql = "CREATE TABLE IF NOT EXISTS lookup_month AS (SELECT JobId,MONTHNAME(STR_TO_DATE(MONTH, '%m')) AS 'Month',LocName,PointsScored,PointsOutOf FROM data); CREATE TABLE IF NOT EXISTS area_a (Month INT, LocName VARCHAR(255), PointsScored INT, PointsOutOf INT); CREATE TABLE IF NOT EXISTS area_b (Month INT, LocName VARCHAR(255), PointsScored INT, PointsOutOf INT); CREATE TABLE IF NOT EXISTS area_c (Month INT, LocName VARCHAR(255), PointsScored INT, PointsOutOf INT); CREATE TABLE IF NOT EXISTS area_fa (Month INT, LocName VARCHAR(255), PointsScored INT, PointsOutOf INT); CREATE TABLE IF NOT EXISTS area_x (Month INT, LocName VARCHAR(255), PointsScored INT, PointsOutOf INT);"; $dbh->query($sql); // Use REPLACE instead so that duplicate values are not inserted into tables $sql = "REPLACE INTO area_a (Month, LocName, PointsScored, PointsOutOf) SELECT Month, LocName, PointsScored, PointsOutOf FROM data WHERE Area = 'Area A'; REPLACE INTO area_b (Month, LocName, PointsScored, PointsOutOf) SELECT Month, LocName, PointsScored, PointsOutOf FROM data WHERE Area = 'Area B'; REPLACE INTO area_c (Month, LocName, PointsScored, PointsOutOf) SELECT Month, LocName, PointsScored, PointsOutOf FROM data WHERE Area = 'Area C'; REPLACE INTO area_fa (Month, LocName, PointsScored, PointsOutOf) SELECT Month, LocName, PointsScored, PointsOutOf FROM data WHERE Area = 'Area FA'; REPLACE INTO area_x (Month, LocName, PointsScored, PointsOutOf) SELECT Month, LocName, PointsScored, PointsOutOf FROM data WHERE Area = 'Area X';"; $dbh->query($sql); } }<file_sep><?php require_once 'createdb.php'; class uploadData extends createDatabase{ public function uploadCsv(){ $field_separator = ","; $line_separator = "\n"; $csv_file = "data/testdata.csv"; if(!file_exists($csv_file)) { die("File not found. Make sure you specified the correct path."); } $sql = "LOAD DATA LOCAL INFILE ".$dbh->quote($csv_file)." REPLACE INTO TABLE `data` FIELDS TERMINATED BY ".$dbh->quote($field_separator)." LINES TERMINATED BY ".$dbh->quote($line_separator); $affected_rows = $dbh->query($sql); } }<file_sep><?php class initialise{ public $db_host = ""; public $db_user = ""; public $db_pass = ""; public $db_name = ""; public $db_table = ""; function connectToDatabase(){ // connect to the database try { $dbh = new PDO("mysql:host=$db_host", $db_user, $db_pass, array(PDO::MYSQL_ATTR_LOCAL_INFILE=>1)); // Enable LOAD INFILE $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } // otherwise throw an exception catch(PDOException $exc) { echo "Error connecting to the database."; file_put_contents('PDOErrors.txt', $exc->getMessage(), FILE_APPEND); } } } <file_sep># PHPReport Generate Client reports using PHP &amp; MySQL. ======= PHPReport v2 <file_sep><?php require_once 'connection.php'; class createDatabase extends initialise{ function createDb(){ $sql = "CREATE DATABASE IF NOT EXISTS `$db_name`; CREATE USER ''@'' IDENTIFIED BY ''; GRANT ALL ON `$db_name`.* TO ''@''; FLUSH PRIVILEGES;"; $dbh->query($sql); // select the new database (short query) $dbh->query("USE $db_name"); // create the initial table. $sql = "CREATE TABLE IF NOT EXISTS $db_table ( JOBID INT( 11 ) NOT NULL, LOCNAME VARCHAR( 50 ) NOT NULL, LOCID INT( 11 ) NOT NULL, AREA VARCHAR( 150 ) NOT NULL, AREAID INT( 11 ) NOT NULL, MONTH INT( 11 ) NOT NULL, POINTSSCORED INT( 11 ) NOT NULL, POINTSOUTOF INT( 11 ) NOT NULL, IDKEY INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (IDKEY));"; $dbh->query($sql); $sql = "ALTER TABLE `DATA` ADD UNIQUE ( `IDKEY`);"; $dbh->query($sql); } }<file_sep><?php $sql = "SELECT * FROM area_a WHERE LocName = 'Loc A';"; $result = $dbh->query($sql); while($row = $result->fetch(PDO::FETCH_BOTH)) { $score[] = $row['PointsScored']; $max[] = $row['PointsOutOf']; } ?> <script> $(function () { $('#pie-container').highcharts({ chart: { plotBackgroundColor: null, plotBorderWidth: null, backgroundColor:'rgba(255, 255, 255, 0.1)', plotShadow: false }, title: { text: 'Data' }, credits: { enabled: false }, tooltip: { pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>' }, plotOptions: { pie: { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true, format: '<b>{point.name}</b>: {point.percentage:.1f} %', style: { color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black' } } } }, series: [{ type: 'pie', name: 'Data', data: [ ['Service', 45.0], ['Satisfaction', 26.8], { name: 'Hygiene', y: 12.8, sliced: true, selected: true }, ['Turnover', 8.5], ['Data', 6.2], ['Rating', 0.7] ] }] }); }); </script><file_sep><?php /** * Created by PhpStorm. * User: crypt * Date: 10/05/2015 * Time: 23:10 */ ?> <script> $(function() { $(document).ready(function() { Highcharts.setOptions({ global: { useUTC: false // Coordinated Universal Time } }); $('#live-container').highcharts({ chart: { type: 'spline', zoomType: 'xy', animation: Highcharts.svg, backgroundColor:'rgba(255, 255, 255, 0.1)', marginRight: 10, events: { load: function() { // Update chart every second var series = this.series[0]; setInterval(function() { var x = (new Date()).getTime(), // current time y = Math.random(); series.addPoint([x, y], true, true); }, 1000); } } }, title: { text: 'Live data' }, credits: { enabled: false }, xAxis: { type: 'datetime', tickPixelInterval: 150 }, yAxis: { title: { text: 'Trading Value' }, plotLines: [{ value: 0, width: 1, color: '#000' }] }, tooltip: { formatter: function() { return '<b>' + this.series.name + '</b><br/>' + Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' + Highcharts.numberFormat(this.y, 2); } }, legend: { enabled: false }, exporting: { enabled: false }, series: [{ name: 'value', data: (function() { // Array of random data var data = [], time = (new Date()).getTime(), i; for (i = -19; i <= 0; i += 1) { data.push({ x: time + i * 1000, y: Math.random() }); } return data; }()) }] }); }); }); </script>
5fbc15197cb5b0f206ff8aa9c6ccdce08dbb7f9f
[ "Markdown", "PHP" ]
10
PHP
Crowles/hgphp
ff17e74ba550459538eab833675f02a9a00306c9
c14a18dd340446f79d8fb2f59b46d39a2c5b40bc
refs/heads/master
<repo_name>Gobinathnagaraj/entry_form<file_sep>/README.md # entry_form ## Description ### This is student data entry form...! #### Screenshot for database ![Image 1](https://github.com/Gobinathnagaraj/entry_form/blob/master/Opera%20Snapshot_2020-08-10_201821_localhost.jpg) #### Screenshot for pageview ![Image 2](https://github.com/Gobinathnagaraj/entry_form/blob/master/db.JPG) <file_sep>/student.sql -- phpMyAdmin SQL Dump -- version 4.9.2 -- https://www.phpmyadmin.net/ -- -- Host: localhost -- Generation Time: Aug 17, 2020 at 03:39 PM -- Server version: 10.4.10-MariaDB -- PHP Version: 7.3.12 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; 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 utf8mb4 */; -- -- Database: `student` -- -- -------------------------------------------------------- -- -- Table structure for table `stu` -- CREATE TABLE `stu` ( `name` varchar(50) NOT NULL, `age` date NOT NULL, `scl` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `stu` -- INSERT INTO `stu` (`name`, `age`, `scl`) VALUES ('dinesh', '2020-08-06', 'ksc'), ('bench', '2020-08-06', 'ksc'); COMMIT; /*!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>/index.php <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <link rel="stylesheet" href="page.css"> <title>Student data entry form</title> </head> <script> function page() { var name = document.forms["form"]["name"]; var age = document.forms["form"]["age"]; var scl = document.forms["form"]["scl"]; if(name.value == "") { name.focus(); windowalert("Name field is required"); return false; } if(age.value == "") { age.focus(); alert("Age field is required"); return false; } if(scl.value == "") { scl.focus(); alert("School field is required"); return false; } return true; } </script> <body> <h2 style="text-align: center;">Student data entry form</h2> <form name="form" action="page.php" onsubmit="return page()" method="POST"> <label>Name:</label> <input id="name" type="text" placeholder="Enter your name" name="name" required><br><br> <label>Standard:</label> <select name="Standard"> <option>10th</option> <option>12th</option> </select><br><br> <label>School:</label> <input id="scl" type="text" placeholder="Enter your school name" name="scl" required> <br><br> <label>Age:</label> <input id="age" type="date" placeholder="Enter your age" name="age" required><br><br> <label>Gender:</label> <select id="gen"> <option>Male</option> <option>Female</option> </select> <h4 style="text-align: center;">Student mark details</h4> <table> <tr> <th>Subject</th> <th>Mark</th> </tr> <tr> <td>Biology</td> <td><input name="bio" type="tel" id="bio" required value="75"></td> </tr> <tr> <td>Computer Science</td> <td><input type="tel" name="com" id="bio" value="75" required></td> </tr> <tr> <td>Mathematics</td> <td><input type="tel" id="bio" value="75" name="math" required></td> </tr> <tr> <td>Physics</td> <td><input type="tel" id="bio" value="75" name="phy" required></td> </tr> <tr> <td>Chemistry</td> <td><input type="tel" id="bio" value="75" name="che" required></td> </tr> </table> <button id="sub" class="btn btn-success" type="submit" name="submit">submit</button> <input id="res" class="btn btn-danger" type="reset" value="reset"> </form> <?php echo "<h1>Your input is: </h1>"; ?> </body> </html> <file_sep>/page.php <?php $dsn = 'mysql:host=localhost;dbname=student'; $username = 'root'; $password = ''; try { $db = new PDO($dsn, $username, $password); } catch (PDOException $e) { $error_message = $e->getMessage(); echo $db->$error_message; exit(); } //inserting data if(isset($_POST['submit'])) { $name = $_POST['name']; $age = $_POST['age']; $school = $_POST['scl']; } if($name !='' && $age !='' && $school !='') { $query = "INSERT INTO stu (name, age, scl) VALUE(?,?,?)"; $stmt = $db->prepare($query); $stmt->execute([$name, $age, $school]); echo 'data stored'; } else{ echo 'insert data fail'. $query."<br>".$db->$e; }
7b63033077592ba1e5c03e06917de408eb3712b2
[ "Markdown", "SQL", "PHP" ]
4
Markdown
Gobinathnagaraj/entry_form
769e182064711863786e42a63cbc14288df620ef
b8d0e07efe1422b1d10681a2bcbe0d0dbcc18bee
refs/heads/master
<file_sep># Rational-Class-Exercise 9.6 (Rational CLass) Create a class called Rational for performing arithmetic with fractions. Write a Program to test your class. Use integer variables to represent the private data of the class -- the numerator and the denominator. Provide a constructor that enables an object of this class to be initialized when it's declared. The constructor should contain default values in case no initializers are provided and should store the fraction in reduced form. For example, the fraction would be stored in the object as 1 in the numerator and 2 in the denominator. Provide public member functions that perform each of the following tasks. a) Adding two Rational Numbers. The result should be stored in reduced form. b) Subtracting two Rational numbers. The result should be stored in reduced form. c) Multiplying two Rational numbers. The result should be stored in reduced form. d) Dividing two Rational numbers. The result should be stored in reduced form. e) Printing Rational numbers in the form a/b, where a is the numerator and b is the denominator. f) Printing Rational numbers in floating-point format. <file_sep>// MAIN_Rational.cpp #include <iostream> #include "Rational.h" using namespace std; int main() { int a = 0, b = 1; Rational F1, F2; cout << "Enter the numerator: "; cin >> a; F1.setNum(a); cout << "Enter the denominator: "; cin >> b; F1.setDem(b); cout << "Enter the numerator: "; cin >> a; F2.setNum(a); cout << "Enter the denominator: "; cin >> b; F2.setDem(b); //Math F1.Add(F2); F1.Subtract(F2); F1.Multiply(F2); F1.Divide(F2); F1.GCD(F2); //Display F1.DisplayFract(F1); F1.DisplayFloat(F1); //Copy Constructor Rational F3(F2); cout << "\n--COPIED FRACTION--" << endl; F3.DisplayFract(F2); system("Pause"); return 0; } // end main. 14 de marzo de 2017 - SUCCESSFUL! /*Output: Enter the numerator: 5 Enter the denominator: 9 Enter the numerator: 10 Enter the denominator: 80 SUM: (5 / 9) + (10 / 80) = (49 / 72) SUBTRACTION: (5 / 9) - (10 / 80) = (31 / 72) MULTIPLICATION: (5 / 9) * (10 / 80) = (5 / 72) DIVISION: (5 / 9) / (10 / 80) = (40 / 9) The fraction (10 / 80) can be simplified to (1 / 8) using the GCD 10. DISPLAY FRACTION: 5 / 9 DISPLAY DECIMAL OF FRACTION: 5 / 9 = 0.555556 --COPIED FRACTION-- DISPLAY FRACTION: 10 / 80 Press any key to continue . . .*/<file_sep>// Rational.h #pragma once #include<iostream> using namespace::std; /* <NAME> #89139 Rational Class Exercise CECS 2222 sec. 22 Prof. <NAME>*/ /*9.6 (Rational CLass) Create a class called Rational for performing arithmetic with fractions. Write a Program to test your class. Use integer variables to represent the private data of the class -- the numerator and the denominator. Provide a constructor that enables an object of this class to be initialized when it's declared. The constructor should contain default values in case no initializers are provided and should store the fraction in reduced form. For example, the fraction would be stored in the object as 1 in the numerator and 2 in the denominator. Provide public member functions that perform each of the following tasks. a) Adding two Rational Numbers. The result should be stored in reduced form. b) Subtracting two Rational numbers. The result should be stored in reduced form. c) Multiplying two Rational numbers. The result should be stored in reduced form. d) Dividing two Rational numbers. The result should be stored in reduced form. e) Printing Rational numbers in the form a/b, where a is the numerator and b is the denominator. f) Printing Rational numbers in floating-point format.*/ class Rational { public: // Constructor & Destructor Rational(int numerator = 0, int denominator = 1); Rational(const Rational &aRational); // Copy Constructor ~Rational(); // Setters void setNum(int a); void setDem(int b); // Getters int getNum() const; int getDem() const; // Math void Add(Rational a1); void Subtract(Rational s1); void Multiply(Rational m1); void Divide(Rational d1); void GCD(Rational g1); // Greatest Common Divider int Simplify(int a, int b); // Display void DisplayFract(Rational f1) const; void DisplayFloat(Rational f2) const; private: int numerator; int denominator; };<file_sep>//Rational.cpp #include <iostream> #include<cmath> #include "Rational.h" using namespace std; //double d2 = (double)i //Constructor & Destructor Rational::Rational(int numerator, int denominator) : numerator(numerator), denominator(denominator) { } //Copy constructor Rational::Rational(const Rational &aRational) { setNum(aRational.getNum()); setDem(aRational.getDem()); //cout << "Copied fraction using the copy constructor." << endl; } Rational::~Rational() { //cout << "Rational object destroyed.\n"; } // Setters void Rational::setNum(int a) { numerator = a; } void Rational::setDem(int b) { denominator = b; } // Getters int Rational::getNum() const { return numerator; } int Rational::getDem() const { return denominator; } // The GDC (Greatest Common Divider) is used in combination with the Simplify Function to determine the number used to make // the fraction smaller but remaining the same value. void Rational::GCD(Rational g1) { int temp = 1, a = g1.getNum(), b = g1.getDem(); if (a < 0) { a *= 1; } else if (b < 0) { b *= -1; } while (b > 0) { temp = b; b = a % temp; a = temp; } cout << "The fraction (" << g1.getNum() << " / " << g1.getDem() << ") can be simplified to (" << g1.getNum() / temp << " / " << g1.getDem() / temp << ") using the GCD " << temp << "." << endl; } // Simplify takes a number that can be made smaller by comparing both numbers. For example the fraction 4/16 can be simplified to 1/4. int Rational::Simplify(int a, int b) { Rational sim; int temp = 1, x, y, r; if (a > b) { x = a; y = b; } else { x = b; y = a; } while (y != 0) { r = x % y; x = y; y = r; } return x; } void Rational::Add(Rational a1) { int cd = getDem() * a1.getDem(); int Num1 = getNum() * a1.getDem(); int Num2 = a1.getNum() * getDem(); cout << "SUM: (" << getNum() << " / " << getDem() << ") + (" << a1.getNum() << " / " << a1.getDem() << ") = (" << (Num1 + Num2) / Simplify(abs(Num1 + Num2), abs(cd)) << " / " << cd / Simplify(abs(Num1 + Num2), abs(cd)) << ")" << endl; } void Rational::Subtract(Rational s1) { int cds = getDem()* s1.getDem(); int Num3 = getNum() * s1.getDem(); int Num4 = s1.getNum() * getDem(); cout << "SUBTRACTION: (" << getNum() << " / " << getDem() << ") - (" << s1.getNum() << " / " << s1.getDem() << ") = (" << (Num3 - Num4) / Simplify(abs(Num3 - Num4), abs(cds)) << " / " << cds / Simplify(abs(Num3 - Num4), abs(cds)) << ")" << endl; } void Rational::Multiply(Rational m1) { int cdr = getDem()* m1.getDem(); int Num5 = getNum() * m1.getNum(); cout << "MULTIPLICATION: (" << getNum() << " / " << getDem() << ") * (" << m1.getNum() << " / " << m1.getDem() << ") = (" << (Num5) / Simplify(abs(Num5), abs(cdr)) << " / " << cdr / Simplify(abs(Num5), abs(cdr)) << ")" << endl; } void Rational::Divide(Rational d1) { int cdd = getDem()* d1.getNum(); int Num6 = getNum() * d1.getDem(); cout << "DIVISION: (" << getNum() << " / " << getDem() << ") / (" << d1.getNum() << " / " << d1.getDem() << ") = (" << (Num6) / Simplify(abs(Num6), abs(cdd)) << " / " << cdd / Simplify(abs(Num6), abs(cdd)) << ")" << endl; } //Display void Rational::DisplayFract(Rational f1) const { cout << "DISPLAY FRACTION: " << f1.getNum() << " / " << f1.getDem() << endl; } void Rational::DisplayFloat(Rational f2) const { double q1 = (double)f2.getNum(); double q2 = (double)f2.getDem(); cout << "DISPLAY DECIMAL OF FRACTION: " << f2.getNum() << " / " << f2.getDem() << " = " << q1 / q2 << endl; }
4b1f0574df9a705e563bc41341e3bedff995760e
[ "Markdown", "C++" ]
4
Markdown
eymelendez/Rational-Class-Exercise
6a8ecb5249720dc61fc5c34bf9d3a441bd160110
099416c8aadcf329c803ad4eba85417c2270e5ee
refs/heads/master
<repo_name>Cheat-Detective-CDT/Repacker<file_sep>/README.md # Repacker 1.14.4+ Minecraft open-source deobfuscator using official Mojang mappings ## Usage `java -jar Repaker.jar <cacheDir> <version>` example: `java -jar Repaker.jar . 1.14.4` **/!\\ This project is designed to be used as a library and not as a executable /!\\** <file_sep>/src/main/java/com/fox2code/repacker/RepackException.java package com.fox2code.repacker; import java.io.IOException; public class RepackException extends IOException { public RepackException() { super(); } public RepackException(String message) { super(message); } } <file_sep>/build.gradle plugins { id 'java' id 'com.github.johnrengelman.shadow' version '4.0.2' } group 'com.fox2code' version '1.0.0' sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { implementation 'org.ow2.asm:asm-commons:7.2' implementation 'com.google.code.gson:gson:2.8.6' } jar { manifest { attributes 'Main-Class': 'com.fox2code.repacker.Main' } } shadowJar { manifest { attributes 'Main-Class': 'com.fox2code.repacker.Main' } } <file_sep>/src/main/java/com/fox2code/repacker/Main.java package com.fox2code.repacker; import java.io.File; import java.io.IOException; public class Main { public static void main(String[] args) { if (args.length != 2) { System.out.println("usage: java -jar Repaker.jar <cacheDir> <version>"); return; } File file = new File(args[0]); if (!file.exists()) { System.out.println("Cache dir doesn't exists!"); return; } try { new Repacker(file).repackClient(args[1]); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } System.exit(0); } }
58979f6bb928022f74c463068666b21bf8a77e38
[ "Markdown", "Java", "Gradle" ]
4
Markdown
Cheat-Detective-CDT/Repacker
350213b65fad2c14228c7e955ff1aa4afa72f499
1f766dbe6d4aaae7de59056d5d3081e726377596
refs/heads/main
<file_sep># Sweaty-Mania 2D Game in LibGDX, OpenGL, LWJGL - Pretty garbage cuz im new to the lib - Uses MIT License - Made by shab <file_sep>package com.mygdx.game; import com.badlogic.gdx.Game; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; public class MyGdxGame extends Game { public BitmapFont font; MainMenuScreen menu; GameOver over; public SpriteBatch batch; @Override public void create () { font = new BitmapFont(); batch = new SpriteBatch(); menu = new MainMenuScreen(this); this.setScreen(menu); } @Override public void render () { super.render(); } @Override public void dispose () { batch.dispose(); font.dispose(); try { menu.gameScreen.dispose(); } catch (Exception e) { System.out.println(e.getMessage()); } } }
af4f9560c51cef1958335bcd2e35789502eefdf4
[ "Markdown", "Java" ]
2
Markdown
shabman/Sweaty-Mania
dccb632f6bccd4c879b5bcbfed282b1638096e11
ffc197eabf44f33c702da7349e133d40dbbd43a0
refs/heads/master
<file_sep>This is a small flask app project that enable tanzania candidates to check their results online by simply searching their student number in full. The project is on going and open source because it is made to help the tanzania socity and not for the need to make any sort of profit Launched via Ngrok for now from https://ngrok.com/ Site now Live at WWW.MATOKEO.ONLINE<file_sep>astroid==2.1.0 bcrypt==3.1.6 beautifulsoup4==4.7.1 blinker==1.4 branca==0.3.1 certifi==2018.11.29 cffi==1.11.5 chardet==3.0.4 Click==7.0 colorama==0.4.1 Django==2.1.5 django-crispy-forms==1.7.2 Flask==1.0.2 Flask-Bcrypt==0.7.1 Flask-Login==0.4.1 Flask-Mail==0.9.1 Flask-SQLAlchemy==2.3.2 Flask-WTF==0.14.2 folium==0.7.0 gunicorn==19.9.0 idna==2.8 isort==4.3.4 itsdangerous==1.1.0 Jinja2==2.10 lazy-object-proxy==1.3.1 MarkupSafe==1.1.0 mccabe==0.6.1 numpy==1.16.0 oauthlib==3.0.1 pandas==0.24.0 pdfkit==0.6.1 Pillow==5.4.1 pipenv==2018.11.26 pycparser==2.19 pylint==2.2.2 PySocks==1.6.8 python-dateutil==2.7.5 pytz==2018.9 requests==2.21.0 requests-oauthlib==1.2.0 six==1.12.0 soupsieve==1.7.3 SQLAlchemy==1.2.17 tweepy==3.7.0 urllib3==1.24.1 virtualenv==16.3.0 virtualenv-clone==0.5.1 Werkzeug==0.14.1 wrapt==1.11.1 WTForms==2.2.1 <file_sep>from flask_wtf import FlaskForm from wtforms import StringField, SubmitField, TextAreaField, SelectField from wtforms.validators import DataRequired, Length class PostForm(FlaskForm): title = StringField('Title', validators=[DataRequired()]) content = TextAreaField('Content', validators=[DataRequired()]) submit = SubmitField('Post') class SearchForm(FlaskForm): name = StringField('Name', validators=[DataRequired()]) year = SelectField(u'Year', choices=[('2017', '2017'), ('2018', '2018'), ('2016', '2016'), ('2015', '2015'), ('2014', '2014'), ('2013', '2013'), ('2012', '2012'), ('2011', '2011'), ('2010', '2010'), ('2009', '2009'), ('2008', '2008'), ('2007', '2007'), ('2008', '2008'), ('2006', '2006'), ('2005', '2005'), ('2004', '2004'), ('2003', '2003'), ('2002', '2002'), ('2001', '2001')]) exam = SelectField(u'Exam', choices=[('csee', 'CSEE'), ('acsee', 'ACSEE'), ('ftna', 'FTNA'), ('ftsee', 'FTSEE'), ('heslb', 'HESLB'), ('psle', 'PSLE'), ('qt', 'QT'), ('sfna', 'SFNA')]) student_number = TextAreaField('Student Number', validators=[DataRequired(), Length(min=10, max=10)]) submit = SubmitField('Search') <file_sep>from flask import (render_template, url_for, flash, redirect, request, abort, Blueprint) from flask_login import current_user, login_required from flaskblog import db from flaskblog.models import Post, Result from flaskblog.posts.forms import PostForm, SearchForm import requests from bs4 import BeautifulSoup import pandas as pd posts = Blueprint('posts', __name__) def numberToResult(iNumber, iYear, iExam): iSchoolnumber = iNumber[:5].lower() iLink = "https://maktaba.tetea.org/exam-results/{exam}{year}/{number}.htm".format(year=iYear, exam=iExam.upper(), number=iSchoolnumber) request = requests.get(iLink) content = request.content soup = BeautifulSoup(content, "html.parser") if (soup.find("font", string=iNumber.upper())): student = soup.find("font", string=iNumber.upper()) else: student = soup.find("font", string=iNumber[6:10].upper()) studentReport = student.parent.parent studentResults = studentReport.find_all("font") studentNumber = studentResults[0].text studentSex = studentResults[1].text studentDivisionPoint = studentResults[2].text studentDivision = studentResults[3].text studentGrades = studentResults[4].text report = soup.find_all("p") schoolReport = report[1].text return{ 'studentNumber': studentNumber, 'studentDivision': studentDivision, 'studentDivisionPoint': studentDivisionPoint, 'studentGrades': studentGrades, 'schoolReport': schoolReport } @posts.route("/post/new", methods=['GET', 'POST']) @login_required def new_post(): form = PostForm() if form.validate_on_submit(): post = Post(title=form.title.data, content=form.content.data, author=current_user) db.session.add(post) db.session.commit() flash('Your post has been created!', 'success') return redirect(url_for('main.home')) return render_template('create_post.html', title='New Post', form=form, legend='New Post') @posts.route("/post/search", methods=['GET', 'POST']) def new_search(): form = SearchForm() if form.validate_on_submit(): name = form.name.data.upper() result = numberToResult(form.student_number.data, form.year.data, form.exam.data.lower()) flash(f"Dear { name },if your number is { form.student_number.data },then below are your results", 'success') return render_template('result.html', title='Preview results', name=name, result=result, legend='Preview Results') return render_template('search_results.html', title='Search Results', form=form, legend='Search Results') @posts.route("/post/<int:post_id>") def post(post_id): post = Post.query.get_or_404(post_id) return render_template('post.html', title=post.title, post=post) @posts.route("/post/<int:post_id>/update", methods=['GET', 'POST']) @login_required def update_post(post_id): post = Post.query.get_or_404(post_id) if post.author != current_user: abort(403) form = PostForm() if form.validate_on_submit(): post.title = form.title.data post.content = form.content.data db.session.commit() flash('Your post has been updated!', 'success') return redirect(url_for('posts.post', post_id=post.id)) elif request.method == 'GET': form.title.data = post.title form.content.data = post.content return render_template('create_post.html', title='Update Post', form=form, legend='Update Post') @posts.route("/post/<int:post_id>/delete", methods=['POST']) @login_required def delete_post(post_id): post = Post.query.get_or_404(post_id) if post.author != current_user: abort(403) db.session.delete(post) db.session.commit() flash('Your post has been deleted!', 'success') return redirect(url_for('main.home'))
22214e4bb93e291605d595c9c01972eaf60cb0b9
[ "Python", "Text" ]
4
Text
Ymcmbennie/Matokeo00
c1d0ca8e97186d071c70d0fa0a4f1fc901b849b1
02a3cb1a49f261f10cdb9d526bdbc6767950d41b
refs/heads/main
<repo_name>riyaz-pasha/ticketing<file_sep>/auth/src/routes/__test__/current-user.test.ts import request from "supertest"; import { app } from "../../app"; const signupRequest = (reqBody: any) => request(app) .post("/api/users/signup") .send(reqBody) const currentUserequest = (cookie: any) => request(app) .get("/api/users/currentuser") .set("Cookie", cookie) .send() it('should responds with the details of the current user', async () => { const email = "<EMAIL>"; const authResponse = await signupRequest({ email: email, password: "<PASSWORD>", }).expect(201); const cookie = authResponse.get("Set-Cookie"); const response = await currentUserequest(cookie) .expect(200) expect(response.body.currentUser).not.toBeNull(); expect(response.body.currentUser.email).toStrictEqual(email); }); it('should responds with null if not authenticated', async () => { const response = await request(app) .get("/api/users/currentuser") .send() .expect(200) expect(response.body.currentUser).toBeNull(); }); <file_sep>/orders/src/routes/__test__/index.test.ts import request from "supertest"; import { app } from "../../app"; import { Ticket } from "../../models/ticket"; import { getId } from "../../test/utils"; const getOrders = (userCookie: string[]) => request(app) .get("/api/orders") .set("Cookie", userCookie) const makeOrder = (ticketId: string, userCookie?: string[]) => request(app) .post("/api/orders") .set("Cookie", userCookie || global.signin()) .send({ ticketId }); const buildTicket = async () => { const ticket = Ticket.build({ title: "Movie Name", price: 100, id: getId() }); await ticket.save(); return ticket; } it('should return orders of the user', async () => { const ticket1 = await buildTicket(); const ticket2 = await buildTicket(); const ticket3 = await buildTicket(); const user1 = global.signin(); const user2 = global.signin(); const { body: user2Order1 } = await makeOrder(ticket2.id, user2); const { body: user2Order2 } = await makeOrder(ticket3.id, user2); const response = await getOrders(user2); expect(response.body.length).toEqual(2); expect(response.body[0].id).toEqual(user2Order1.id); expect(response.body[0].ticket.id).toEqual(ticket2.id); expect(response.body[1].id).toEqual(user2Order2.id); expect(response.body[1].ticket.id).toEqual(ticket3.id); });<file_sep>/orders/src/routes/__test__/new.test.ts import request from 'supertest'; import { app } from '../../app'; import { Order, OrderStatus } from '../../models/order'; import { Ticket } from '../../models/ticket'; import { getId } from "../../test/utils"; const makeOrder = (ticketId: string, userCookie?: string[]) => request(app) .post("/api/orders") .set("Cookie", userCookie || global.signin()) .send({ ticketId }); it('should return an error if the ticket does not exists', async () => { const ticketId = getId(); const response = await makeOrder(ticketId); expect(response.status).toEqual(404); expect(response.body.errors[0].message).toEqual("Not Found"); }); it('should return an error if ticket is already reserved', async () => { const ticket = Ticket.build({ title: "Movie Name", price: 100, id: getId() }); await ticket.save(); const order = Order.build({ ticket, userId: "asdfasdf", status: OrderStatus.Created, expiresAt: new Date() }); await order.save(); const response = await makeOrder(ticket.id); expect(response.status).toEqual(400); expect(response.body.errors[0].message).toEqual("Ticket is already reserved"); }); it('should reserves a ticket', async () => { const ticket = Ticket.build({ title: "Movie Name", price: 100, id: getId(), }); await ticket.save(); const response = await makeOrder(ticket.id); expect(response.status).toEqual(201); expect(response.body).toHaveProperty("status"); expect(response.body).toHaveProperty("expiresAt"); expect(response.body).toHaveProperty("userId"); expect(response.body).toHaveProperty("ticket"); }); it('should emit an order created event', async () => { const ticket = Ticket.build({ title: "Movie Name", price: 100, id: getId(), }); await ticket.save(); const response = await makeOrder(ticket.id); expect(response.status).toEqual(201); }); <file_sep>/expiration/src/events/publishers/expiration-complete-publisher.ts import { ExpirationCompleteEvent, Publisher, Subjects } from "@riyazpasha/ticketing-common"; class ExpirationCompletePublisher extends Publisher<ExpirationCompleteEvent>{ subject: Subjects.ExpirationComplete = Subjects.ExpirationComplete; } export { ExpirationCompletePublisher, }; <file_sep>/tickets/src/event/pubishers/ticket-updated-publisher.ts import { Publisher, Subjects, TicketUpdatedEvent } from "@riyazpasha/ticketing-common"; class TicketUpdatedPublisher extends Publisher<TicketUpdatedEvent>{ subject: Subjects.TicketUpdated = Subjects.TicketUpdated; } export { TicketUpdatedPublisher, }; <file_sep>/auth/src/routes/__test__/signup.test.ts import request from "supertest"; import { app } from "../../app"; const signupRequest = (reqBody: any) => request(app) .post("/api/users/signup") .send(reqBody) it('should return a 201 response on succcessful signup', async () => { return request(app) .post("/api/users/signup") .send({ email: "<EMAIL>", password: "<PASSWORD>", }) .expect(201) }); it('should disallow duplicate signups', async () => { await signupRequest({ email: "<EMAIL>", password: "<PASSWORD>", }).expect(201) await signupRequest({ email: "<EMAIL>", password: "<PASSWORD>", }).expect(400) }); it('should set cookie on successful signup', async () => { const response = await signupRequest({ email: "<EMAIL>", password: "<PASSWORD>", }).expect(201) expect(response.get("Set-Cookie")).toBeDefined(); }); it('should return a 400 when in valid email is passed', async () => { return signupRequest({ email: "test", password: "<PASSWORD>", }).expect(400) }); it('should return a 400 when in valid password is passed', async () => { return signupRequest({ email: "<EMAIL>", password: "p", }).expect(400) }); it('should return a 400 when email & password are missing', async () => { return signupRequest({}) .expect(400) }); it('should return a 400 when email is missing', async () => { return signupRequest({ password: "<PASSWORD>", }).expect(400) }); it('should return a 400 when password is missing', async () => { return signupRequest({ email: "<EMAIL>", }).expect(400) }); <file_sep>/orders/src/routes/__test__/show.test.ts import request from "supertest"; import { app } from "../../app"; import { Ticket } from "../../models/ticket"; import { getId } from "../../test/utils"; const getOrderById = (orderId: string, userCookie: string[]) => request(app) .get(`/api/orders/${orderId}`) .set("Cookie", userCookie) const makeOrder = (ticketId: string, userCookie?: string[]) => request(app) .post("/api/orders") .set("Cookie", userCookie || global.signin()) .send({ ticketId }); const buildTicket = async () => { const ticket = Ticket.build({ title: "Movie Name", price: 100, id: getId(), }); await ticket.save(); return ticket; } it('should fetch order details', async () => { const ticket1 = await buildTicket(); const user1 = global.signin(); const { body: user1Order1 } = await makeOrder(ticket1.id, user1); const response = await getOrderById(user1Order1.id, user1); expect(response.status).toEqual(200); expect(response.body).toEqual(user1Order1); }); it('should not fetch other user order details', async () => { const ticket1 = await buildTicket(); const user1 = global.signin(); const user2 = global.signin(); const { body: user1Order1 } = await makeOrder(ticket1.id, user1); const response = await getOrderById(user1Order1.id, user2); expect(response.status).toEqual(401); expect(response.body.errors[0].message).toEqual("Not authorized"); }); <file_sep>/tickets/src/routes/__test__/new.test.ts import { Subjects } from "@riyazpasha/ticketing-common"; import request from "supertest"; import { app } from "../../app" import { Ticket } from "../../models/ticket"; import { natsWrapper } from "../../nats-wrapper"; it('should have a route handler listening to /api/tickets for post requests', async () => { const response = await request(app) .post("/api/tickets") .send({}) expect(response.status).not.toEqual(404); }); it('can only be accessed if the user is signed in', async () => { const response = await request(app) .post("/api/tickets") .send({}) expect(response.status).toEqual(401); expect(response.unauthorized).toBeTruthy(); expect(response.text).toContain("Not authorized"); }); it('should not return not authorized error when user is logged in', async () => { const response = await request(app) .post("/api/tickets") .set("Cookie", global.signin()) .send({}) expect(response.status).not.toEqual(401); expect(response.unauthorized).not.toBeTruthy(); expect(response.text).not.toContain("Not authorized"); }); it('should return an error if empty title is provided', async () => { const response = await request(app) .post("/api/tickets") .set("Cookie", global.signin()) .send({ title: "", price: 10, }) expect(response.status).toEqual(400); expect(response.text).toContain("Title is required"); }); it('should return an error if no title is provided', async () => { const response = await request(app) .post("/api/tickets") .set("Cookie", global.signin()) .send({ price: 10, }) expect(response.status).toEqual(400); expect(response.text).toContain("Title is required"); }); it('should return an error if 0 is provided as price', async () => { const response = await request(app) .post("/api/tickets") .set("Cookie", global.signin()) .send({ title: "title", price: 0, }) expect(response.status).toEqual(400); expect(response.text).toContain("Price must be greater than 0"); }); it('should return an error if proce is not provided', async () => { const response = await request(app) .post("/api/tickets") .set("Cookie", global.signin()) .send({ title: "title", }) expect(response.status).toEqual(400); expect(response.text).toContain("Price must be greater than 0"); }); it('should create a new ticket when valid inputs are passed', async () => { const title = "title"; const price = 123; let tickets = await Ticket.find({}); expect(tickets.length).toEqual(0); const response = await request(app) .post("/api/tickets") .set("Cookie", global.signin()) .send({ title, price, }) expect(response.status).toEqual(201); tickets = await Ticket.find({}); expect(tickets.length).toEqual(1); expect(tickets[0].title).toEqual(title); expect(tickets[0].price).toEqual(price); }); it('should publish an event on successful ticket creation', async () => { const title = "title"; const price = 123; const response = await request(app) .post("/api/tickets") .set("Cookie", global.signin()) .send({ title, price, }) expect(response.status).toEqual(201); expect(natsWrapper.client.publish).toHaveBeenCalledTimes(1); }); <file_sep>/payments/src/events/listeners/queue-group-name.ts const queueGroupName = "payments-service"; export { queueGroupName, }; <file_sep>/tickets/src/routes/__test__/index.test.ts import request from 'supertest'; import { app } from '../../app'; const getTickets = () => request(app) .get(`/api/tickets`) .send() const creatTicket = (body: { title: string, price: number }) => request(app) .post("/api/tickets") .set("Cookie", global.signin()) .send(body) const creatRandomTicket = () => creatTicket({ title: "title", price: 1 }) it('should fetch all the tickets', async () => { await creatRandomTicket(); await creatRandomTicket(); await creatRandomTicket(); const response = await getTickets(); expect(response.status).toStrictEqual(200); expect(response.body.length).toStrictEqual(3); }); <file_sep>/tickets/src/routes/__test__/show.test.ts import mongoose from 'mongoose'; import request from 'supertest'; import { app } from '../../app'; const getTicketById = (id: string) => request(app) .get(`/api/tickets/${id}`) .send() const creatTicket = (body: { title: string, price: number }) => request(app) .post("/api/tickets") .set("Cookie", global.signin()) .send(body) const getId = () => new mongoose.Types.ObjectId().toHexString(); it('should return a 404 when ticket it not found', async () => { const id = getId(); await getTicketById(id) .expect(404) }); it('should the ticket if ticket is found', async () => { const title = "title"; const price = 123; const createTicketResponse = await creatTicket({ title, price }) .expect(201) const response = await getTicketById(createTicketResponse.body.id); expect(response.status).toEqual(200); expect(response.body.title).toEqual(title); expect(response.body.price).toEqual(price); }); <file_sep>/expiration/src/events/listeners/queue-group-name.ts const queueGroupName = "expiration-service"; export { queueGroupName, }; <file_sep>/payments/src/test/utils.ts import mongoose from 'mongoose'; const getId = () => new mongoose.Types.ObjectId().toHexString(); export { getId, }; <file_sep>/auth/src/routes/__test__/signout.test.ts import request from "supertest"; import { app } from "../../app"; const signupRequest = (reqBody: any) => request(app) .post("/api/users/signup") .send(reqBody) const signoutRequest = (reqBody: any) => request(app) .post("/api/users/signout") .send(reqBody) it('should clears the cookie after signing out', async () => { const signupResponse = await signupRequest({ email: "<EMAIL>", password: "<PASSWORD>", }).expect(201) expect(signupResponse.get("Set-Cookie")).toBeDefined(); const response = await signoutRequest({}) .expect(200) expect(response.get("Set-Cookie")[0]) .toEqual('express:sess=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; httponly'); });<file_sep>/tickets/src/event/listeners/queue-group-name.ts const queueGroupName = "tickets-service"; export { queueGroupName, }; <file_sep>/orders/src/events/publishers/order-created-publisher.ts import { OrderCreatedEvent, Publisher, Subjects } from "@riyazpasha/ticketing-common"; class OrderCreatedPublisher extends Publisher<OrderCreatedEvent>{ subject: Subjects.OrderCreated = Subjects.OrderCreated; } export { OrderCreatedPublisher, }; <file_sep>/orders/src/events/listeners/queue-group-name.ts const queueGroupName = "orders-service"; export { queueGroupName, }; <file_sep>/payments/src/routes/__test__/new.test.ts import { OrderStatus } from '@riyazpasha/ticketing-common'; import request from 'supertest'; import { app } from '../../app'; import { Order } from '../../models/order'; import { Payment } from '../../models/payment'; import { stripe } from '../../stripe'; import { getId } from '../../test/utils'; const purchace = (data: any, cookie: string[]) => request(app) .post("/api/payments") .set("Cookie", cookie) .send(data) it('should return a 404 when purchasing a order that doesnot exists', async () => { const order = { token: "token", orderId: getId(), } const response = await purchace(order, global.signin()); expect(response.status).toBe(404); expect(response.body.errors[0].message).toEqual("Not Found"); }); it('should return a 401 when purchacing an order that doesnot belong to the user', async () => { const order = Order.build({ id: getId(), version: 0, userId: getId(), status: OrderStatus.Created, price: 100, }); await order.save(); const placeOrder = { token: "token", orderId: order.id, } const response = await purchace(placeOrder, global.signin()); expect(response.status).toBe(401); expect(response.body.errors[0].message).toEqual("Not authorized"); }); it('should return a 400 when purchacing a cancelled order', async () => { const userId = getId(); const order = Order.build({ id: getId(), version: 0, userId: userId, status: OrderStatus.Cancelled, price: 100, }); await order.save(); const placeOrder = { token: "token", orderId: order.id, } const response = await purchace(placeOrder, global.signin(userId)); expect(response.status).toBe(400); expect(response.body.errors[0].message).toEqual("Can not pay for cancelled order"); }); it('should make payment when valid input is supplied', async () => { const userId = getId(); const order = Order.build({ id: getId(), version: 0, userId: userId, status: OrderStatus.Created, price: 100, }); await order.save(); const placeOrder = { token: "tok_<PASSWORD>", orderId: order.id, } const response = await purchace(placeOrder, global.signin(userId)); expect(stripe.charges.create).toHaveBeenCalledTimes(1); expect(stripe.charges.create).toHaveBeenCalledWith({ currency: "usd", amount: order.price * 100, source: placeOrder.token, }); expect(response.status).toBe(201); }); it('should store payment details on succesful payment with stripe', async () => { const userId = getId(); const order = Order.build({ id: getId(), version: 0, userId: userId, status: OrderStatus.Created, price: 100, }); await order.save(); const placeOrder = { token: "tok_<PASSWORD>", orderId: order.id, } const response = await purchace(placeOrder, global.signin(userId)); expect(response.status).toBe(201); const payment = await Payment.findOne({ orderId: order.id }); expect(payment).toBeDefined(); expect(payment).toHaveProperty("orderId", order.id); expect(payment).toHaveProperty("stripeId"); }); <file_sep>/nats-test/src/events/ticket-created-publisher.ts import { Publisher } from "./base-publisher"; import { Subjects } from "./Subjects"; import { TicketCreatedEvent } from "./ticket-created-event"; class TickerCreatedPublisher extends Publisher<TicketCreatedEvent>{ subject: Subjects.TickerCreated = Subjects.TickerCreated; } export { TickerCreatedPublisher, }; <file_sep>/orders/src/routes/__test__/delete.test.ts import { Subjects } from "@riyazpasha/ticketing-common"; import request from "supertest"; import { app } from "../../app"; import { Order, OrderStatus } from "../../models/order"; import { Ticket } from "../../models/ticket"; import { natsWrapper } from "../../nats-wrapper"; import { getId } from "../../test/utils"; const deleteOrderById = (orderId: string, userCookie: string[]) => request(app) .delete(`/api/orders/${orderId}`) .set("Cookie", userCookie) .send() const makeOrder = (ticketId: string, userCookie?: string[]) => request(app) .post("/api/orders") .set("Cookie", userCookie || global.signin()) .send({ ticketId }); const buildTicket = async () => { const ticket = Ticket.build({ title: "Movie Name", price: 100, id: getId() }); await ticket.save(); return ticket; } it('should change the status of order to cancelled', async () => { const ticket1 = await buildTicket(); const user1 = global.signin(); const { body: user1Order1 } = await makeOrder(ticket1.id, user1); const response = await deleteOrderById(user1Order1.id, user1); expect(response.status).toEqual(204); const updatedOrder = await Order.findById(user1Order1.id); expect(updatedOrder?.status).toEqual(OrderStatus.Cancelled); }); it('should not cancel other user order details', async () => { const ticket1 = await buildTicket(); const user1 = global.signin(); const user2 = global.signin(); const { body: user1Order1 } = await makeOrder(ticket1.id, user1); const response = await deleteOrderById(user1Order1.id, user2); expect(response.status).toEqual(401); expect(response.body.errors[0].message).toEqual("Not authorized"); }); it('should order cancelled event', async () => { const ticket1 = await buildTicket(); const user1 = global.signin(); const { body: user1Order1 } = await makeOrder(ticket1.id, user1); const response = await deleteOrderById(user1Order1.id, user1); expect(response.status).toEqual(204); // @ts-ignore expect(natsWrapper.client.publish.mock.calls[1][0]).toStrictEqual(Subjects.OrderCancelled); }); <file_sep>/tickets/src/routes/__test__/update.test.ts import request from 'supertest'; import { app } from '../../app'; import { Ticket } from '../../models/ticket'; import { getId } from '../../test/utils'; type TicketAttrs = { title?: string; price?: number; }; let user1cookie: string[] = [""]; const ticketDetails = { title: "title", price: 1 }; const updateTicket = (id: string, body: TicketAttrs, cookie: string[]) => request(app) .put(`/api/tickets/${id}`) .set("Cookie", cookie) .send(body) const creatTicket = (body: TicketAttrs, cookie: string[]) => request(app) .post("/api/tickets") .set("Cookie", cookie) .send(body) const getTicketById = (id: string) => request(app) .get(`/api/tickets/${id}`) .send() beforeAll(() => { user1cookie = global.signin(); }) it('should return 401 if user is not authenticated', async () => { const usercookie = [""]; const id = getId(); const updateTicketDetails = { title: "new-title", price: 1 }; const response = await updateTicket(id, updateTicketDetails, usercookie) expect(response.status).toStrictEqual(401); expect(response.body.errors[0].message).toStrictEqual("Not authorized"); }); it('should return 404 if provided id doesnot exist', async () => { const id = getId(); const updatedTicketDetails = { title: "new-title", price: 1 }; const response = await updateTicket(id, updatedTicketDetails, user1cookie) expect(response.status).toStrictEqual(404); expect(response.body.errors[0].message).toStrictEqual("Not Found"); }); it('should return 401 if user doesnot own the ticket', async () => { const user2cookie = global.signin(); const updatedTicketDetails = { title: "new-title", price: 1 }; const createTicketResponse = await creatTicket(ticketDetails, user1cookie); const response = await updateTicket(createTicketResponse.body.id, updatedTicketDetails, user2cookie); expect(response.status).toStrictEqual(401); expect(response.body.errors[0].message).toStrictEqual("Not authorized"); }); it('should return an error if empty title is provided', async () => { const updatedTicketDetails = { title: "", price: 1 }; const createTicketResponse = await creatTicket(ticketDetails, user1cookie); const response = await updateTicket(createTicketResponse.body.id, updatedTicketDetails, user1cookie); expect(response.status).toEqual(400); expect(response.body.errors[0].message).toContain("Title is required"); }); it('should return an error if no title is provided', async () => { const updatedTicketDetails = { price: 1 }; const createTicketResponse = await creatTicket(ticketDetails, user1cookie); const response = await updateTicket(createTicketResponse.body.id, updatedTicketDetails, user1cookie); expect(response.status).toEqual(400); expect(response.body.errors[0].message).toContain("Title is required"); }); it('should return an error if 0 is provided as price', async () => { const updatedTicketDetails = { title: "", price: 0 }; const createTicketResponse = await creatTicket(ticketDetails, user1cookie); const response = await updateTicket(createTicketResponse.body.id, updatedTicketDetails, user1cookie); expect(response.status).toEqual(400); expect(response.text).toContain("Price must be greater than 0"); }); it('should return an error if price is not provided', async () => { const updatedTicketDetails = { title: "title" }; const createTicketResponse = await creatTicket(ticketDetails, user1cookie); const response = await updateTicket(createTicketResponse.body.id, updatedTicketDetails, user1cookie); expect(response.status).toEqual(400); expect(response.text).toContain("Price must be greater than 0"); }); it('should update the ticket when valid details is provided', async () => { const title = "new-title"; const price = 100; const updatedTicketDetails = { title, price }; const createTicketResponse = await creatTicket(ticketDetails, user1cookie).expect(201); const updateResponse = await updateTicket(createTicketResponse.body.id, updatedTicketDetails, user1cookie); expect(updateResponse.status).toEqual(200); const response = await getTicketById(createTicketResponse.body.id); expect(response.status).toEqual(200); expect(response.body.title).toEqual(title); expect(response.body.price).toEqual(price); }); it('should not allow the user to edit the ticket which is reserved', async () => { const updatedTicketDetails = { title: "new-title", price: 1 }; const createTicketResponse = await creatTicket(ticketDetails, user1cookie).expect(201); const ticket = await Ticket.findById(createTicketResponse.body.id); const orderId = getId(); ticket?.set({ orderId }); await ticket?.save(); const response = await updateTicket(createTicketResponse.body.id, updatedTicketDetails, user1cookie) expect(response.status).toStrictEqual(400); expect(response.body.errors[0].message).toStrictEqual("Cannot edit a reserved Ticket"); }); <file_sep>/auth/src/routes/__test__/signin.test.ts import request from "supertest"; import { app } from "../../app"; const signupRequest = (reqBody: any) => request(app) .post("/api/users/signup") .send(reqBody) const signinRequest = (reqBody: any) => request(app) .post("/api/users/signin") .send(reqBody) it('should return status 400 when a email that doesnot exists is supplied', async () => { return signinRequest({ email: "<EMAIL>", password: "<PASSWORD>", }).expect(400) }); it('should return status 400 when incorrect password is supplied', async () => { await signupRequest({ email: "<EMAIL>", password: "<PASSWORD>", }).expect(201) await signinRequest({ email: "<EMAIL>", password: "<PASSWORD>", }).expect(400) }); it('should respond with a cookie when valid credentials supplied', async () => { await signupRequest({ email: "<EMAIL>", password: "<PASSWORD>", }).expect(201) const response = await signinRequest({ email: "<EMAIL>", password: "<PASSWORD>", }).expect(200) expect(response.get("Set-Cookie")).toBeDefined(); }); <file_sep>/orders/src/utils/validation.ts import mongoose from 'mongoose'; const isValidTicketId = (ticketId: string) => { return mongoose.Types.ObjectId.isValid(ticketId); } export { isValidTicketId, };
92e46904ab2bd052756b9b888bc09a29eb82cc0f
[ "TypeScript" ]
23
TypeScript
riyaz-pasha/ticketing
2167b220fc5c52ca18f5bebea9e21a2ddc59e0d4
5c41cfc3f30e8c074c6b7ba490d368bd0c2baefe
refs/heads/master
<repo_name>adlele/es6-msteams-samples-yelp-integration-nodejs<file_sep>/src/bot.js import * as builder from 'botbuilder'; import * as teams from 'botbuilder-teams'; import config from 'config'; var connector; export default class Echobot { static setup(app) { if (!config.has("bot.appId")) { // We are running locally; fix up the location of the config directory and re-intialize config process.env.NODE_CONFIG_DIR = "../config"; delete require.cache[require.resolve('config')]; config = require('config'); } // Create a connector to handle the conversations connector = new teams.TeamsChatConnector({ // It is a bad idea to store secrets in config files. We try to read the settings from // the config file (/config/default.json) OR then environment variables. // See node config module (https://www.npmjs.com/package/config) on how to create config files for your Node.js environment. appId: config.get("bot.appId"), appPassword: config.get("bot.appPassword") }); const inMemoryBotStorage = new builder.MemoryBotStorage(); // Define a simple bot with the above connector that echoes what it received const bot = new builder.UniversalBot(connector, session => { // Message might contain @mentions which we would like to strip off in the response const text = teams.TeamsMessage.getTextWithoutMentions(session.message); session.send('You said: %s', text); }).set('storage', inMemoryBotStorage); // Setup an endpoint on the router for the bot to listen. // NOTE: This endpoint cannot be changed and must be api/messages app.post('/api/messages', connector.listen()); } } export {connector} // export default function setup(app) { // const builder = require('botbuilder'); // const teams = require('botbuilder-teams'); // let config = require('config'); // if (!config.has("bot.appId")) { // // We are running locally; fix up the location of the config directory and re-intialize config // process.env.NODE_CONFIG_DIR = "../config"; // delete require.cache[require.resolve('config')]; // config = require('config'); // } // // Create a connector to handle the conversations // const connector = new teams.TeamsChatConnector({ // // It is a bad idea to store secrets in config files. We try to read the settings from // // the config file (/config/default.json) OR then environment variables. // // See node config module (https://www.npmjs.com/package/config) on how to create config files for your Node.js environment. // appId: config.get("bot.appId"), // appPassword: config.get("bot.appPassword") // }); // const inMemoryBotStorage = new builder.MemoryBotStorage(); // // Define a simple bot with the above connector that echoes what it received // const bot = new builder.UniversalBot(connector, session => { // // Message might contain @mentions which we would like to strip off in the response // const text = teams.TeamsMessage.getTextWithoutMentions(session.message); // session.send('You said: %s', text); // }).set('storage', inMemoryBotStorage); // // Setup an endpoint on the router for the bot to listen. // // NOTE: This endpoint cannot be changed and must be api/messages // app.post('/api/messages', connector.listen()); // // Export the connector for any downstream integration - e.g. registering a messaging extension // export {connector} // }
0d32b506ba71b8b2d82651d39d3c21febe79f58a
[ "JavaScript" ]
1
JavaScript
adlele/es6-msteams-samples-yelp-integration-nodejs
9499d1dc9a4f684963f7c7de96512537e3e9778d
21cf0a15d11c67c5c8ced3018845b4b8c6bf3aa0
refs/heads/master
<file_sep>/* * Observer pattern */ public abstract class CoordinateSubject { protected Ship observer; // TODO // update the observer // read about the observer pattern // // I couldn't call a ship. Attempted to research the observer pattern // before and during the exam, but had no success. Tried updating the // ship in order to hit and remove life to satisfy the test, but satisfying // the two failing tests (testShipCanBeObservedOnMultipleCoordinates and // testShipOnCoordinateCanBeHit) caused null pointer exceptions in two other // tests (testCallingCoordinateSetsCalled and testCoordinateMissesWhenNoShipIsOnIt). // I tried my best to satisfy all of the coordinate tests, but I couldn't. I spent // most of my time in class attempting to find the solution for my nullPointerExceptions // which was where I was stuck when working on this assessment outside of class. // public void notifyObserver() throws Exception { this.observer.update(); } public Ship getObservable() { return this.observer; } public void attach(Ship observer) { this.observer = observer; } }
5d93d12c5e0d1f35483e4934a64766fbcb12d509
[ "Java" ]
1
Java
trev0115/Vandise-agile-sp2018-oop
290f9d15e15c0fce109cbf540e4991adbe4f1665
e334c0d068348b0ecb2354588d115e037d27f377
refs/heads/master
<file_sep>class Solution: def removeDuplicates(self, nums: List[int]) -> int: n = len(nums) if n == 0: return 0 i, j = 0, 0 while j < n: k = 1 v = nums[j] j += 1 while j < n and nums[j] == v: j += 1 k += 1 k = min(2, k) while k > 0: nums[i] = v i += 1 k -= 1 return i<file_sep>class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: index = {} n = len(nums) for j in range(n): num = nums[j] i = index.get(num, -k-1) if j - i <= k: return True index[num] = j return False <file_sep>class Solution: def colorBorder(self, grid: List[List[int]], r0: int, c0: int, color: int) -> List[List[int]]: color0 = grid[r0][c0] m, n = len(grid), len(grid[0]) q = [(r0, c0)] vis = [[False]*n for i in range(m)] vis[r0][c0] = True border = [] while len(q) > 0: x, y = q.pop() k = 0 if x-1 >= 0 and grid[x-1][y] == color0: if not vis[x-1][y]: q.append((x-1, y)) vis[x-1][y] = True k += 1 if x+1 < m and grid[x+1][y] == color0: if not vis[x+1][y]: q.append((x+1, y)) vis[x+1][y] = True k += 1 if y-1 >= 0 and grid[x][y-1] == color0: if not vis[x][y-1]: q.append((x, y-1)) vis[x][y-1] = True k += 1 if y+1 < n and grid[x][y+1] == color0: if not vis[x][y+1]: q.append((x, y+1)) vis[x][y+1] = True k += 1 if k != 4: border.append((x, y)) for x,y in border: grid[x][y] = color return grid <file_sep>class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: n = numCourses inCount = [0] * n #outCount = [0] * n edge = [[] for i in range(n)] for a,b in prerequisites: inCount[a] += 1 #outCount[b] += 1 edge[b].append(a) ret = [] q = [] for i in range(n): if inCount[i] == 0: q.append(i) while len(q) > 0: x = q.pop() ret.append(x) for e in edge[x]: inCount[e] -= 1 if inCount[e] == 0: q.append(e) if len(ret) != n: ret = [] return ret <file_sep>class Solution(object): def minimumSwap(self, s1, s2): """ :type s1: str :type s2: str :rtype: int """ if len(s1) != len(s2): return -1 n = len(s1) x, y = 0, 0 for i in range(n): if s1[i] == s2[i]: continue if s1[i] == 'x': x += 1 else: y += 1 if (x + y)&1 == 1: return -1 return (x >> 1) + (y >> 1) + (x % 2) + (y % 2) <file_sep>class Solution: def maxAreaOfIsland(self, grid: List[List[int]]) -> int: res = 0 m, n = len(grid), len(grid[0]) visited = [[False] * n for _ in range(m)] def dfs(x, y): if x < 0 or x >= m or y < 0 or y >= n: return 0 if grid[x][y] == 0 or visited[x][y]: return 0 visited[x][y] = True return dfs(x+1, y) + dfs(x-1, y) + dfs(x, y+1) + dfs(x, y-1) + 1 for i in range(m): for j in range(n): area = dfs(i, j) res = max(res, area) return res<file_sep>class Solution(object): def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ l1, l2 = len(nums1), len(nums2) n = l1 + l2 def lower_bound(a, l, r, v): while l < r: m = (l + r) / 2 if a[m] >= v: r = m else: l = m + 1 return r def upper_bound(a, l, r, v): while l < r: m = (l + r) / 2 if a[m] > v: r = m else: l = m + 1 return r def get_idx(v): i1, r1 = lower_bound(nums1, 0, l1, v), upper_bound(nums1, 0, l1, v) i2, r2 = lower_bound(nums2, 0, l2, v), upper_bound(nums2, 0, l2 ,v) return [i1 + i2, r1 + r2] def findkth(a, l, r, k): while l < r: m = (l + r) / 2 idx = get_idx(a[m]) if idx[0] <= k and idx[1] > k: return a[m] elif idx[1] <= k: l = m + 1 else: #idx[0] > k r = m return None def findkth2(k): x = findkth(nums1, 0, l1, k) if x is None: x = findkth(nums2, 0, l2, k) return x if n&1 == 1: ret = findkth2(n/2) else: x = findkth2(n/2 - 1) y = findkth2(n/2) ret = (x + y) / 2.0 return ret <file_sep>class NumArray(object): def __init__(self, nums): """ :type nums: List[int] """ self.n = len(nums) self.sums = [0] * (self.n * 4) if self.n > 0: self.init_sums(1, 0, self.n-1, nums) def init_sums(self, root, l, r, nums): if l == r: self.sums[root] = nums[l] else: m = (l + r) / 2 self.init_sums(root<<1, l, m, nums) self.init_sums(root<<1|1, m+1, r, nums) self.sums[root] = self.sums[root<<1] + self.sums[root<<1|1] def update(self, i, val): """ :type i: int :type val: int :rtype: void """ self._update(1, 0, self.n-1, i, val) def _update(self, root, l, r, i, val): if l == r: self.sums[root] = val else: m = (l + r) / 2 if i <= m: self._update(root<<1, l, m, i, val) else: self._update(root<<1|1, m+1, r, i, val) self.sums[root] = self.sums[root<<1] + self.sums[root<<1|1] def sumRange(self, i, j): """ :type i: int :type j: int :rtype: int """ return self._query(1, 0, self.n-1, i, j) def _query(self, root, l, r, i, j): if l>=i and r <=j: return self.sums[root] if l>j or r < i: return 0 m = (l + r) / 2 return self._query(root<<1, l, m, i, j) + self._query(root<<1|1, m+1, r, i, j) # Your NumArray object will be instantiated and called as such: # obj = NumArray(nums) # obj.update(i,val) # param_2 = obj.sumRange(i,j)<file_sep># @param {Integer[]} nums # @param {Integer} k # @return {Integer} def find_pairs(nums, k) return 0 if k < 0 h = Hash.new(0) ret = 0 nums.each do |i| h[i] += 1 end h.each do |x,y| if k == 0 if y > 1 then ret += 1 end else if h[x+k] > 0 then ret += 1 end end end return ret end puts find_pairs([1,2,3,4,5], -1)<file_sep>class Solution: def simplifiedFractions(self, n: int) -> List[str]: def gcd(a, b): return b if a%b == 0 else gcd(b, a%b) ret = [] for i in range(1, n): for j in range(i+1, n+1): if gcd(i, j) == 1: ret.append(f'{i}/{j}') return ret<file_sep>class Solution: def letterCombinations(self, digits: str) -> List[str]: if len(digits) == 0: return [] letters = [ 0,0, 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz' ] ret = [''] for digit in digits: ret2 = [] for letter in letters[int(digit)]: for s in ret: ret2.append(s+letter) ret = ret2 return ret<file_sep># Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def sortedListToBST(self, head: ListNode) -> TreeNode: nodes = [] while head: nodes.append(head) head = head.next def toBST(i, j): if i > j: return None if i == j: return TreeNode(nodes[i].val) k = (i + j) // 2 root = TreeNode(nodes[k].val) root.left = toBST(i, k-1) root.right = toBST(k+1, j) return root return toBST(0, len(nodes)-1) <file_sep>class Solution(object): def findDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) l, r = 1, n-1 def count(p): lt, gt = 0, 0 for i in nums: if i <= p: lt += 1 else: gt += 1 if lt>p: return -1 else: return 1 ret = l while l<=r: m = (l+r)/2 k = count(m) if k<0: ret = m r = m-1 else: l = m+1 ret = m+1 return ret <file_sep>class Solution: def combine(self, n: int, k: int) -> List[List[int]]: ret = [] q = [[i] for i in range(1, n+1)] while len(q) > 0: q2 = [] for comb in q: if len(comb) == k: ret.append(comb) elif n - comb[-1] >= k - len(comb): for i in range(comb[-1]+1, n+1): comb2 = comb[:] comb2.append(i) q2.append(comb2) q = q2 return ret<file_sep>class Solution: def minSteps(self, n: int) -> int: ret = 0 for i in range(2, n+1): while n % i == 0: ret += i n = n // i return ret<file_sep>class Solution: def simplifyPath(self, path: str) -> str: dirs = path.split('/') new_dirs = [] for d in dirs: if d == '' or d == '.': continue if d == '..': if len(new_dirs) > 0: new_dirs.pop() else: new_dirs.append(d) return '/' + '/'.join(new_dirs) <file_sep>class Solution: def generate(self, numRows: int) -> List[List[int]]: ret = [[1]] for n in range(1, numRows): row = [1] * (n + 1) for i in range(1, n): row[i] = ret[-1][i-1] + ret[-1][i] ret.append(row) return ret <file_sep>class Solution: def dailyTemperatures(self, temperatures: List[int]) -> List[int]: n = len(temperatures) ret = [0] * n q = [] for i in range(n): while len(q) > 0 and temperatures[q[-1]] < temperatures[i]: ret[q[-1]] = i - q[-1] q.pop() q.append(i) return ret <file_sep>class Solution(object): def spiralOrder(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ if (not matrix) or (not matrix[0]): return [] m = len(matrix) n = len(matrix[0]) ret = [] k = 0 while len(ret) < m*n: i, j = k, k while j < n-k: ret.append(matrix[i][j]) j += 1 i, j = k+1, n-k-1 while i < m-k: ret.append(matrix[i][j]) i += 1 i, j = m-1-k, n-k-2 while i>k and j >= k: ret.append(matrix[i][j]) j -= 1 i, j = m-1-k-1, k while i>k and j<n-k-1: ret.append(matrix[i][j]) i -= 1 k += 1 return ret <file_sep>class Solution: def sortArray(self, nums: List[int]) -> List[int]: def mergeSort(arr, l, r): if l >= r: return arr[l:r+1] m = (l + r) // 2 a1 = mergeSort(arr, l, m) a2 = mergeSort(arr, m+1, r) i, j = 0, 0 l1, l2 = len(a1), len(a2) ret = [] while i < l1 and j < l2: if a1[i] <= a2[j]: ret.append(a1[i]) i += 1 else: ret.append(a2[j]) j += 1 if i < l1: ret += a1[i:] elif j < l2: ret += a2[j:] return ret return mergeSort(nums, 0, len(nums)-1)<file_sep>class Solution: def minIncrementForUnique(self, nums: List[int]) -> int: nums.sort() ret = 0 k = -1 for num in nums: if num <= k: k += 1 ret += k - num k = max(num, k) return ret<file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def printTree(self, root: TreeNode) -> List[List[str]]: def getHeight(node): if not node: return 0 return max(getHeight(node.left), getHeight(node.right)) + 1 height = getHeight(root) m = height n = (1 << m) - 1 #print(m, n) ret = [] q = [(root, 0, n)] if height > 0 else [] while len(q) > 0: q2 = [] row = [''] * n for node, left, right in q: mid = (left + right) >> 1 row[mid] = str(node.val) if node.left: q2.append((node.left, left, mid-1)) if node.right: q2.append((node.right, mid+1, right)) q = q2 ret.append(row) return ret<file_sep>class Solution: def reorderedPowerOf2(self, n: int) -> bool: return ''.join(sorted(list(str(n)))) in set([''.join(sorted(list(str(1<<i)))) for i in range(32)])<file_sep>class Twitter(object): def __init__(self): """ Initialize your data structure here. """ self.tweets = [] self.follows = {} def postTweet(self, userId, tweetId): """ Compose a new tweet. :type userId: int :type tweetId: int :rtype: void """ self.tweets.append((userId, tweetId)) def getNewsFeed(self, userId): """ Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. :type userId: int :rtype: List[int] """ ret = [] follow = self._getfollows(userId) for t in self.tweets[::-1]: if t[0] == userId or t[0] in follow: ret.append(t[1]) if len(ret) == 10: break return ret def follow(self, followerId, followeeId): """ Follower follows a followee. If the operation is invalid, it should be a no-op. :type followerId: int :type followeeId: int :rtype: void """ if followerId != followeeId: self._getfollows(followerId).add(followeeId) def unfollow(self, followerId, followeeId): """ Follower unfollows a followee. If the operation is invalid, it should be a no-op. :type followerId: int :type followeeId: int :rtype: void """ if followeeId in self._getfollows(followerId): self._getfollows(followerId).remove(followeeId) def _getfollows(self, id): if self.follows.get(id, None) is None: self.follows[id] = set() return self.follows[id] # Your Twitter object will be instantiated and called as such: # obj = Twitter() # obj.postTweet(userId,tweetId) # param_2 = obj.getNewsFeed(userId) # obj.follow(followerId,followeeId) # obj.unfollow(followerId,followeeId)<file_sep>class Solution: def largestRectangleArea(self, heights: List[int]) -> int: n = len(heights) left = [0] * n right = [0] * n stack = [] for i in range(n): while len(stack) > 0 and heights[stack[-1]] >= heights[i]: stack.pop() if len(stack) > 0: left[i] = stack[-1]+1 else: left[i] = 0 stack.append(i) stack = [] for i in range(n-1, -1, -1): while len(stack) > 0 and heights[stack[-1]] >= heights[i]: stack.pop() if len(stack) > 0: right[i] = stack[-1]-1 else: right[i] = n-1 stack.append(i) res = 0 for i in range(n): res = max(res, (right[i]-left[i]+1) * heights[i]) return res<file_sep>class Solution: def majorityElement(self, nums: List[int]) -> List[int]: d = {} for i in nums: d[i] = d.get(i, 0) + 1 k = len(nums)//3 return [i for i in d if d[i] > k]<file_sep>type NumArray struct { nums []int sums []int } func lowbit(x int) int { return x & (-x) } func (this *NumArray) sum(x int) int { res := 0 for i := x; i > 0; i -= lowbit(i) { res += this.sums[i] } return res } func Constructor(nums []int) NumArray { arr := NumArray{ nums: make([]int, len(nums)), sums: make([]int, len(nums)+1), } for i := 0; i < len(nums); i++ { arr.Update(i, nums[i]) } return arr } func (this *NumArray) Update(index int, val int) { delta := val - this.nums[index] this.nums[index] = val for i := index + 1; i < len(this.sums); i += lowbit(i) { this.sums[i] += delta } } func (this *NumArray) SumRange(left int, right int) int { return this.sum(right+1) - this.sum(left) } /** * Your NumArray object will be instantiated and called as such: * obj := Constructor(nums); * obj.Update(index,val); * param_2 := obj.SumRange(left,right); */ /** * Your NumMatrix object will be instantiated and called as such: * obj := Constructor(matrix); * param_1 := obj.SumRegion(row1,col1,row2,col2); */ <file_sep>func fractionToDecimal(numerator int, denominator int) string { var num, deno int64 = int64(numerator), int64(denominator) if num%deno == 0 { return strconv.FormatInt(num/deno, 10) } var res string if (num < 0) != (deno < 0) { res += "-" } if num < 0 { num = -num } if deno < 0 { deno = -deno } res += strconv.FormatInt(num/deno, 10) res += "." num = num % deno nums := make(map[int64]int) for num != 0 { if _, ok := nums[num]; ok { res = res[:nums[num]] + "(" + res[nums[num]:] + ")" break } nums[num] = len(res) num *= 10 res += strconv.FormatInt(num/deno, 10) num %= deno } return res }<file_sep>class Solution: def addStrings(self, num1: str, num2: str) -> str: res = [] m, n = len(num1), len(num2) num1, num2 = num1[::-1], num2[::-1] i, j, k = 0, 0, 0 while i < m or j < n: a, b = 0, 0 if i < m: a = int(num1[i]) if j < n: b = int(num2[j]) k = k + a + b res.append(str(k % 10)) k = k // 10 i, j = i+1, j+1 if k >0: res.append(str(k)) return "".join(res[::-1]) <file_sep>class Solution: def deckRevealedIncreasing(self, deck: List[int]) -> List[int]: from collections import deque de = deque([]) deck.sort(reverse=True) for i in deck: if len(de) > 1: r = de.pop() de.appendleft(r) de.appendleft(i) return list(de)<file_sep>func maximalSquare(matrix [][]byte) int { res := 0 m, n := len(matrix), len(matrix[0]) dp := make([][]int, m+1) for i := 0; i < m+1; i++ { dp[i] = make([]int, n+1) } for i := 1; i <= m; i++ { for j := 1; j <= n; j++ { // sum of left, top, dp[i][j] = int(matrix[i-1][j-1]-'0') + dp[i-1][j] + dp[i][j-1] - dp[i-1][j-1] } } for i := 1; i <= m; i++ { for j := 1; j <= n; j++ { for k := 0; k+i <= m && k+j <= n; k++ { sum := dp[i+k][j+k] - dp[i-1][j+k] - dp[i+k][j-1] + dp[i-1][j-1] if sum == (k+1)*(k+1) && sum > res { res = sum } } } } return res } <file_sep># Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def splitListToParts(self, root: ListNode, k: int) -> List[ListNode]: ret = [] n = 0 r = root while r: n += 1 r = r.next if k >= n: ret = [None for i in range(k)] for i in range(n): ret[i] = root root = root.next ret[i].next = None return ret for i in range(k): pre = root ret.append(root) if i < n%k: root = root.next for j in range(n//k): pre = root root = root.next pre.next = None return ret<file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def smallestFromLeaf(self, root: TreeNode) -> str: f = {} q = [root] leaf = [] while len(q) > 0: r = q.pop() child = 0 if r.left: f[r.left] = r q.append(r.left) child += 1 if r.right: f[r.right] = r q.append(r.right) child += 1 if child == 0: leaf.append(r) leaf.sort(key=lambda x: x.val) strs = [] for r in leaf: if r.val != leaf[0].val: break s = [] while r: s.append(chr(r.val + ord('a'))) r = f.get(r, None) strs.append(''.join(s)) strs.sort() return strs[0]<file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def findFrequentTreeSum(self, root: TreeNode) -> List[int]: from collections import defaultdict freq = defaultdict(int) def find(node): if not node: return 0 s = node.val + find(node.left) + find(node.right) freq[s] += 1 return s find(root) maxFreq = max(freq.values()) return [k for k, v in filter(lambda x: x[1] == maxFreq, freq.items())] <file_sep>class Solution: def checkPossibility(self, nums: List[int]) -> bool: n = len(nums) less = 0 for i in range(1, n): if nums[i] < nums[i-1]: less += 1 if (less > 1) or (i-2>=0 and i+1<n and nums[i+1] < nums[i-1] and nums[i] < nums[i-2]): return False return True<file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def maxAncestorDiff(self, root: TreeNode) -> int: ret = 0 q = [[root, root.val, root.val]] while len(q) > 0: node, val1, val2 = q.pop() ret = max(ret, abs(val1 - node.val), abs(val2 - node.val)) val1, val2 = max(val1, node.val), min(val2, node.val) if node.left: q.append([node.left, val1, val2]) if node.right: q.append([node.right, val1, val2]) return ret<file_sep># Definition for a undirected graph node # class UndirectedGraphNode: # def __init__(self, x): # self.label = x # self.neighbors = [] class Solution: # @param node, a undirected graph node # @return a undirected graph node def cloneGraph(self, node): self.d = {} ret = self._dfs(node) return ret def _dfs(self, node): if node is None: return None if node in self.d: return self.d[node] newnode = UndirectedGraphNode(node.label) self.d[node] = newnode for i in node.neighbors: newnode.neighbors.append(self._dfs(i)) return newnode <file_sep>func nthSuperUglyNumber(n int, primes []int) int { ugly := make([]int, n) ugly[0] = 1 index := make([]int, len(primes)) nums := make([]int, len(primes)) min := 0 for i := 1; i < n; i++ { min = math.MaxInt32 for j := 0; j < len(primes); j++ { nums[j] = ugly[index[j]] * primes[j] if nums[j] < min { min = nums[j] } } ugly[i] = min for j := 0; j < len(primes); j++ { if nums[j] == min { index[j]++ } } } return ugly[n-1] }<file_sep>class Solution: def minSteps(self, s: str, t: str) -> int: from collections import defaultdict s_chars, t_chars = defaultdict(int), defaultdict(int) ret = 0 for c in s: s_chars[c] += 1 for c in t: t_chars[c] += 1 for c, count in t_chars.items(): ret += max(0, count-s_chars.get(c, 0)) return ret <file_sep>class Solution: def permuteUnique(self, nums: List[int]) -> List[List[int]]: def nextPermutation(ns): i = len(ns)-1 while i-1 >= 0 and ns[i-1] >= ns[i]: i -= 1 if i == 0: return None j = len(ns)-1 while ns[j] <= ns[i-1]: j -= 1 ns[i-1], ns[j] = ns[j], ns[i-1] j = len(ns)-1 while i < j: ns[i], ns[j] = ns[j], ns[i] i += 1 j -= 1 return ns nums.sort() ret = [nums[:]] while True: x = nextPermutation(nums) if not x: break ret.append(x[:]) return ret <file_sep>class Solution: def maximumProduct(self, nums: List[int]) -> int: nums.sort() res = nums[0] * nums[1] * nums[2] for i in range(4): product = nums[2-i] * nums[1-i] * nums[0-i] res = max(res, product) return res<file_sep>class Solution(object): def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ if numRows <=0: return [] ret = [[1]] for i in range(1, numRows): ret.append([1] + [ ret[-1][i] + ret[-1][i+1] for i in range(0, i-1)] + [1]) return ret<file_sep>func canMeasureWater(jug1Capacity int, jug2Capacity int, targetCapacity int) bool { var gcd func(int, int) int gcd = func(a, b int) int { if b == 0 { return a } return gcd(b, a%b) } return targetCapacity <= jug1Capacity+jug2Capacity && targetCapacity%gcd(jug1Capacity, jug2Capacity) == 0 }<file_sep>class Solution: def longestOnes(self, A: List[int], K: int) -> int: n = len(A) i, j = 0, 0 zero = 0 ret = 0 while j < n: if A[j] == 0: zero += 1 while i < j and zero > K: if A[i] == 0: zero -= 1 i += 1 if zero <= K: ret = max(ret, j-i+1) j += 1 return ret<file_sep>class Solution(object): def frequencySort(self, s): """ :type s: str :rtype: str """ fp = {} for c in s: fp[c] = fp.get(c, 0) + 1 def cmp(a, b): if fp[a] == fp[b]: return ord(a) - ord(b) else: return fp[b] - fp[a] s = list(s) s.sort(cmp=cmp) return ''.join(s) <file_sep>class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: n = len(nums) s = 0 res = -float('inf') for i in range(n): if i > k-1: s -= nums[i-k] s += nums[i] print(s) if i >= k-1: res = max(res, s/k) return res <file_sep>class Solution: def islandPerimeter(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) res = 0 def neighbors(x, y): cnt = 0 for dx, dy in ((1, 0), (0, 1), (-1, 0), (0, -1)): x2, y2 = x+dx, y+dy if x2>=0 and x2<m and y2>=0 and y2<n and grid[x2][y2] == 1: cnt += 1 return cnt for i in range(m): for j in range(n): if grid[i][j] == 0: continue res += 4 - neighbors(i, j) return res <file_sep>class Solution: def numTeams(self, rating: List[int]) -> int: from collections import defaultdict n = len(rating) greater = defaultdict(int) def merge(arr): if len(arr) < 2: return arr m = len(arr) // 2 a = merge(arr[:m]) b = merge(arr[m:]) i, j = 0, 0 while i < len(a) and j < len(b): if a[i] < b[j]: arr[i+j] = a[i] greater[a[i]] += len(b) - j i += 1 else: arr[i+j] = b[j] j += 1 while i < len(a): arr[i+j] = a[i] i += 1 while j < len(b): arr[i+j] = b[j] j += 1 return arr merge(rating[:]) ret = 0 for i in range(n): for j in range(i+1, n): if rating[i] < rating[j]: #print(rating[i], rating[j], greater[rating[j]]) ret += greater[rating[j]] else: ret += n - j - 1 - greater[rating[j]] return ret<file_sep>class Solution: def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]: m1 = {} for i in range(len(list1)): m1[list1[i]] = i commnStr, commonSum = [], len(list1) + len(list2) for i in range(len(list2)): s = list2[i] if s in m1: j = m1[s] if i + j == commonSum: commnStr.append(s) elif i + j < commonSum: commonSum = i + j commnStr = [s] return commnStr<file_sep>class Solution { public: int hIndex(vector<int>& citations) { int n = citations.size(); int l = 0, r = n, m,x = 0; while (l<=r) { m = (l+r)/2; if (citations.end() - lower_bound(citations.begin(), citations.end(), m) >= m) { x = m; l = m + 1; } else { r = m - 1; } } return x; } };<file_sep>class Solution: def minFallingPathSum(self, matrix: List[List[int]]) -> int: n = len(matrix) r1, r2 = [0] * n, [0] * n for row in matrix: for i in range(n): r2[i] = r1[i] + row[i] if i > 0: r2[i] = min(r2[i], row[i] + r1[i-1]) if i < n - 1: r2[i] = min(r2[i], row[i] + r1[i+1]) r1, r2 = r2, r1 return min(r1)<file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: index = {} for i, num in enumerate(inorder): index[num] = i def build(i, j, l, r): if i>j or l >r: return None k = index[preorder[i]] n = k - l node = TreeNode(preorder[i]) node.left = build(i+1, i+n, l, k-1) node.right = build(i+n+1, j, k+1, r) return node return build(0, len(preorder)-1, 0, len(preorder)-1)<file_sep># Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def isPalindrome(self, head): """ :type head: ListNode :rtype: bool """ def reverse_list(h): if h is None or h.next is None: return h p = None while h: h2 = h.next h.next = p p = h h = h2 return p if head is None: return True if head.next is None: return True mid, h = head, head mp = None while h and h.next: mp = mid mid = mid.next h = h.next.next if h is None and mp: mp.next = None h1 = head h2 = reverse_list(mid) print(h1.val, h2.val) while h1: if h1.val != h2.val: return False h1 = h1.next h2 = h2.next return True <file_sep># @param {Integer[]} flowerbed # @param {Integer} n # @return {Boolean} def can_place_flowers(flowerbed, n) cnt = 0 len = flowerbed.length i = 0 k = 0 while i < len if flowerbed[i]==1 i += 1 next end while i+k < len && flowerbed[i+k] == 0 k += 1 end x = k - 2 + 1 if i==0 x += 1 end if i+k==len x += 1 end if x >0 cnt += x/2 end i+=k k=0 end cnt >= n end <file_sep>class Solution: def findDuplicate(self, paths: List[str]) -> List[List[str]]: from collections import defaultdict all_files = defaultdict(list) for path in paths: files = path.split(' ') root = files[0] for file in files[1:]: lp_index = file.index('(') filename, content = file[:lp_index], file[lp_index+1:-1] full_path = f'{root}/{filename}' all_files[content].append(full_path) return list(filter(lambda x:len(x) > 1, all_files.values()))<file_sep>class ListNode: def __init__(self, key, value): self.previous = None self.next = None self.key = key self.value = value class List: def __init__(self): self.node = ListNode(0,0) self.node.previous, self.node.next = self.node, self.node @property def head(self): return self.node.next @property def tail(self): return self.node.previous def remove(self, node): l, r = node.previous, node.next l.next, r.previous = r, l def insertToHead(self, node): l, r = self.node, self.node.next node.previous, node.next = l, r l.next, r.previous = node, node class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.cache = {} self.list = List() def get(self, key: int) -> int: if key in self.cache: node = self.cache[key] self.list.remove(node) self.list.insertToHead(node) return node.value else: return -1 def put(self, key: int, value: int) -> None: if key in self.cache: node = self.cache[key] node.value = value self.list.remove(node) self.list.insertToHead(node) else: if len(self.cache) == self.capacity: del self.cache[self.list.tail.key] node = self.list.tail node.key, node.value = key, value self.list.remove(node) else: node = ListNode(key, value) self.cache[key] = node self.list.insertToHead(node) # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)<file_sep># Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: m, n = 0, 0 taila, tailb = None, None h = headA while h: taila = h m += 1 h = h.next h = headB while h: tailb = h n += 1 h = h.next if taila != tailb: return None if m > n: for i in range(m-n): headA = headA.next else: for i in range(n - m): headB = headB.next while headA != headB: headA = headA.next headB = headB.next return headA <file_sep>class Solution: def isNStraightHand(self, hand: List[int], groupSize: int) -> bool: from collections import defaultdict n = len(hand) if n % groupSize != 0: return False count = defaultdict(int) for num in hand: count[num] += 1 hand.sort() for num in hand: if count[num] == 0: continue for i in range(num, num+groupSize): if count[i] == 0: return False count[i] -= 1 return True <file_sep>class Solution: def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]: return sorted(points, key=lambda x: x[0]*x[0]+x[1]*x[1])[:K]<file_sep>""" # Definition for a QuadTree node. class Node: def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight): self.val = val self.isLeaf = isLeaf self.topLeft = topLeft self.topRight = topRight self.bottomLeft = bottomLeft self.bottomRight = bottomRight """ class Solution: def construct(self, grid: List[List[int]]) -> 'Node': def construct_node(x1, y1, x2, y2) -> Node | int: if x2 - x1 == 1 or y2 - y1 == 1: return grid[x1][y1] x0 = (x1 + x2) // 2 y0 = (y1 + y2) // 2 topLeft = construct_node(x1, y1, x0, y0) topRight = construct_node(x1, y0, x0, y2) bottomLeft = construct_node(x0, y1, x2, y0) bottomRight = construct_node(x0, y0, x2, y2) if topLeft == topRight == bottomLeft == bottomRight: return topLeft nodes = [topLeft, topRight, bottomLeft, bottomRight] for i in range(4): if not isinstance(nodes[i], Node): nodes[i] = Node(nodes[i], True, None, None, None, None) return Node(1, False, *nodes) n = len(grid) node = construct_node(0, 0, n, n) if not isinstance(node, Node): node = Node(node, True, None, None, None, None) return node <file_sep>class Solution: def subdomainVisits(self, cpdomains: List[str]) -> List[str]: from collections import defaultdict ret = defaultdict(int) for cpdomain in cpdomains: count, cpdomain = cpdomain.split(' ') count = int(count) dots = cpdomain.split('.') for i in range(len(dots)): domain = '.'.join(dots[i:]) ret[domain] += count return [f'{count} {domain}' for domain, count in ret.items()]<file_sep>class Solution: def numRollsToTarget(self, d: int, f: int, target: int) -> int: dp = [0]*(target+1) dp[0] = 1 for i in range(d): for j in range(target, i, -1): dp[j] = 0 for k in range(1, f+1): if j-k >=i: dp[j] += dp[j-k] dp[j] %= 1000000007 return dp[target] <file_sep>class Solution: def getMoneyAmount(self, n: int) -> int: dp = [[-1 for i in range(n+1)] for i in range(n+1)] def guess(i, j): if i == j: return 0 if i + 1 == j: return i if dp[i][j] == -1: dp[i][j] = min([k + max(guess(i, k-1), guess(k+1, j)) for k in range(i+1, j)]) return dp[i][j] return guess(1, n) <file_sep>class Solution: def numRabbits(self, answers: List[int]) -> int: ret = 0 rabbits = {} for ans in answers: if ans == 0: ret += 1 elif ans in rabbits: rabbits[ans] = rabbits[ans] - 1 if rabbits[ans] == 0: del rabbits[ans] else: rabbits[ans] = ans ret += ans+1 return ret<file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]: to_delete = set(to_delete) ret = [] if root.val in to_delete else [root] def getForest(node): if not node: return None node.left = getForest(node.left) node.right = getForest(node.right) if node.val in to_delete: if node.left and (node.left not in to_delete): ret.append(node.left) if node.right and (node.right not in to_delete): ret.append(node.right) return None return node getForest(root) return ret <file_sep>class Solution: def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]: f = lambda x: x.count(min(x)) queries = [f(q) for q in queries] words = [f(w) for w in words] q = [0] * (max(max(words), max(queries)) + 2) for w in words: q[w] += 1 for i in range(len(q)-2, 0, -1): q[i] += q[i+1] return [q[i+1] for i in queries]<file_sep>class Solution: def isIdealPermutation(self, A): """ :type A: List[int] :rtype: bool """ for i, j in enumerate(A): if (abs(i - j) > 1): return False return True <file_sep>class Solution: def reversePairs(self, nums: List[int]) -> int: def binarySearch(arr, l, r, x): while l < r: m = (l + r)// 2 if arr[m] <= x: l = m + 1 else: r = m return l def mergeSort(arr): n = len(arr) if n <= 1: return arr, 0 m = n // 2 a, x = mergeSort(arr[:m]) b, y = mergeSort(arr[m:]) ret = x + y l, r = 0, len(a) for num in b: l = binarySearch(a,l, r, num * 2) ret += len(a) - l i, j = 0, 0 while i < len(a) and j < len(b): if a[i] <= b[j]: arr[i+j] = a[i] i += 1 else: arr[i+j] = b[j] j += 1 while i < len(a): arr[i+j] = a[i] i += 1 while j < len(b): arr[i+j] = b[j] j += 1 return arr, ret _, ret = mergeSort(nums) return ret <file_sep>func minWindow(s string, t string) string { m, n := len(s), len(t) if m < n { return "" } res := "" nChar := 0 chars := [128]int{} for i := 0; i < n; i++ { if chars[t[i]] == 0 { nChar++ } chars[t[i]]++ } l := 0 subChars := [128]int{} for i := 0; i < m; i++ { if chars[s[i]] == 0 { continue } subChars[s[i]]++ if subChars[s[i]] == chars[s[i]] { nChar-- } for l <= i && (chars[s[l]] == 0 || subChars[s[l]] > chars[s[l]]) { subChars[s[l]]-- l++ } if nChar == 0 && (res == "" || i-l+1 < len(res)) { res = s[l : i+1] } } return res }<file_sep>class Solution(object): def nextGreaterElement(self, findNums, nums): """ :type findNums: List[int] :type nums: List[int] :rtype: List[int] """ stack = [] greater = {} for i in nums: while len(stack) > 0 and i > stack[-1]: greater[stack.pop()] = i stack.append(i) for i in stack: greater[i] = -1 return [greater[i] for i in findNums] <file_sep>class Solution: def fractionToDecimal(self, numerator: int, denominator: int) -> str: a, b = numerator, denominator flag = '' if a * b < 0: flag = '-' a, b = abs(a), abs(b) c = a // b d = a % b if d == 0: return flag + str(c) x = str(c) y = '' ds = set() dl = [] while d != 0: if d in ds: i = dl.index(d) ret = flag + x + '.' + y[:i] + '(' + y[i:] + ')' return ret dl.append(d) ds.add(d) a = d * 10 c = a // b d = a % b y += str(c) if d == 0: return flag + x + '.' + y<file_sep>class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: n = len(s) wordDict = set(wordDict) dp = [False] * (n + 1) q = [0] while len(q) >0: start = q.pop() for i in range(start+1, min(n+1, start+20)): if s[start:i] in wordDict and (not dp[i]): dp[i] = True q.append(i) return dp[n] <file_sep>class Solution: def matrixScore(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) ret = m * (1 << (n - 1)) for i in range(m): if grid[i][0] == 1: continue for j in range(n): grid[i][j] ^= 1 for j in range(1, n): v = 0 for i in range(m): v += grid[i][j] ret += max(v, m-v) * (1 <<(n-1-j)) return ret <file_sep>class Solution: def lengthLongestPath(self, input: str) -> int: lines = input.split('\n') maxPathLen = 0 dirs = [] for line in lines: t = line.count('\t') # file if '.' in line: if t == 0: maxPathLen = max(maxPathLen, len(line)) else: path = dirs[t-1] + '/' + line[t:] #print(path) maxPathLen = max(maxPathLen, len(path)) # dir else: if t == len(dirs): dirs.append('') if t == 0: dirs[0] = line else: dirs[t] = dirs[t-1] + '/' + line[t:] #print(dirs) return maxPathLen <file_sep>class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ for i in range(m): nums1[-i-1] = nums1[m-i-1] i, j = 0, 0 while i < m or j < n: if j >= n or (i < m and nums1[i+n] <= nums2[j]): nums1[i+j] = nums1[i+n] i += 1 else: nums1[i+j] = nums2[j] j += 1 <file_sep>class Solution: def candy(self, ratings: List[int]) -> int: n = len(ratings) candy = [1] * n rank = list(range(n)) rank.sort(key=lambda x: ratings[x]) for i in rank: if i > 0 and ratings[i] > ratings[i-1]: candy[i] = max(candy[i], candy[i-1] + 1) if i < n - 1 and ratings[i] > ratings[i+1]: candy[i] = max(candy[i], candy[i+1] + 1) return sum(candy)<file_sep>class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: n = len(nums) def kth(l, r): if nums[l] > nums[r]: nums[l], nums[r] = nums[r], nums[l] p = nums[l] i, j = l, r while i < j: while i < r and nums[i] <= p: i += 1 while j > l and nums[j] > p: j -= 1 if i < j: nums[i], nums[j] = nums[j], nums[i] i += 1 j -= 1 else: break if i > j: i, j = j, i nums[l] = nums[i] nums[i] = p #print(nums, i, j, p) if n - k == i: return nums[i] if n - k < i: return kth(l, i-1) else: return kth(i+1, r) return kth(0, n-1)<file_sep>func solveSudoku(board [][]byte) { rows := [10][10]bool{} cols := [10][10]bool{} grids := [3][3][10]bool{} for i := 0; i < 9; i++ { for j := 0; j < 9; j++ { k := board[i][j] - '0' if k > 0 && k <= 9 { rows[i][k] = true cols[j][k] = true grids[i/3][j/3][k] = true } } } var dfs func(int, int) bool dfs = func(i, j int) bool { if i == 9 { return true } if board[i][j] != '.' { return dfs(i+(j+1)/9, (j+1)%9) } for k := 1; k <= 9; k++ { if rows[i][k] || cols[j][k] || grids[i/3][j/3][k] { continue } board[i][j] = byte(k + '0') rows[i][k] = true cols[j][k] = true grids[i/3][j/3][k] = true if dfs(i+(j+1)/9, (j+1)%9) { return true } board[i][j] = '.' rows[i][k] = false cols[j][k] = false grids[i/3][j/3][k] = false } return false } dfs(0, 0) }<file_sep># Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def largestValues(self, root): """ :type root: TreeNode :rtype: List[int] """ ret = [] st = [] if root: st = [root] while len(st)>0: st2 = [] mx = st[0].val for t in st: mx=max(mx, t.val) if t.left: st2.append(t.left) if t.right: st2.append(t.right) st = st2 ret.append(mx) return ret <file_sep># Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def getAllElements(self, root1, root2): """ :type root1: TreeNode :type root2: TreeNode :rtype: List[int] """ import heapq def traverse(node): q = [] while node: q.append(node) node = node.left while len(q) > 0: x = q.pop() yield x.val node = x.right while node: q.append(node) node = node.left a, b = traverse(root1), traverse(root2) return list(heapq.merge(a, b))<file_sep>class Solution: def countServers(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) row = [0] * m ret = 0 for i in range(m): s = sum(grid[i]) if s > 1: ret += s row[i] = 1 for j in range(n): s = 0 s2 = 0 for i in range(m): s += grid[i][j] s2 += grid[i][j] & row[i] if s > 1: ret += s - s2 return ret <file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Queue: def __init__(self): self.a = [] self.b = [] def size(self): return len(self.a) + len(self.b) def push(self, x): self.b.append(x) def pop(self): if len(self.a) == 0: self.a = self.b self.a.reverse() self.b = [] return self.a.pop() class Solution: def isCompleteTree(self, root: TreeNode) -> bool: if not root: return True q = Queue() q.push(root) while q.size() > 0: node = q.pop() if node.left and node.right: q.push(node.left) q.push(node.right) elif (not node.left) and node.right: return False elif (node.left and (not node.right)) or ((not node.left) and (not node.right)): if node.left and (not node.right): q.push(node.left) while q.size() > 0: node = q.pop() if node.left or node.right: return False return True<file_sep>class Solution: def prisonAfterNDays(self, cells: List[int], N: int) -> List[int]: def cells2int(cs): ret = 0 for i in range(8): ret += cs[i] * (1 << i) return ret def int2cells(num): cs = [0] * 8 for i in range(8): if num & (1<<i) > 0: cs[i] = 1 return cs ci = cells2int(cells) status = set([ci]) status2 = [ci] while 1: cells2 = list(cells) cells2[0] = cells2[-1] = 0 for i in range(1, 7): if cells[i-1] + cells[i+1] in [0, 2]: cells2[i] = 1 else: cells2[i] = 0 if len(status) == N: return cells2 ci = cells2int(cells2) if ci in status: i = status2.index(ci) status2 = status2[i:] N -= i break status.add(ci) status2.append(ci) cells = cells2 ci = status2[N%len(status2)] return int2cells(ci)<file_sep>class Queue: def __init__(self): self.a = [] self.b = [] def append(self, x): self.a.append(x) def pop(self): if len(self.b) == 0: self.a, self.b = self.b, self.a self.b.reverse() return self.b.pop() def __len__(self): return len(self.a) + len(self.b) class Solution: def openLock(self, deadends: List[str], target: str) -> int: deadends = set(deadends) if '0000' in deadends: return -1 codes = set('0000') q = Queue() q.append(('0000', 0)) while len(q) > 0: code, step = q.pop() if code == target: return step for i in range(4): newcode = [int(num) for num in code] newcode[i] = (newcode[i] + 1) % 10 newcode = ''.join([str(num) for num in newcode]) if (newcode not in deadends) and (newcode not in codes): codes.add(newcode) q.append((newcode, step + 1)) newcode = [int(num) for num in code] newcode[i] = (newcode[i] - 1) % 10 newcode = ''.join([str(num) for num in newcode]) if (newcode not in deadends) and (newcode not in codes): codes.add(newcode) q.append((newcode, step + 1)) return -1<file_sep>class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: if len(pushed) != len(popped): return False popped.reverse() stack = [] for i in pushed: stack.append(i) while len(stack) > 0 and stack[-1] == popped[-1]: stack.pop() popped.pop() return len(stack) == 0 <file_sep>func wiggleMaxLength(nums []int) int { n := len(nums) if n < 2 { return n } res := 1 preNum := nums[0] lastDiff := 0 for i := 1; i < n; i++ { if nums[i] == preNum { continue } if res == 1 { res++ lastDiff = nums[i] - preNum preNum = nums[i] } else { diff := nums[i] - preNum if diff*lastDiff < 0 { res++ } lastDiff = diff preNum = nums[i] } } return res }<file_sep># Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: if not head: return head n = 0 h = head tail = h while h: tail = h n += 1 h = h.next k = k % n if k == 0: return head tail.next = head m = n - k - 1 h = head while m > 0: m -= 1 h = h.next head = h.next h.next = None return head <file_sep>class Solution(object): def numDecodings(self, s): """ :type s: str :rtype: int """ if s is None : return 0 if len(s) == 0: return 0 if s[0] == '0': return 0 n = len(s) dp = [0] * (n+1) dp[0] = 1 for i in range(n): if s[i] == '0': #error if s[i-1] != '1' and s[i-1] != '2': return 0 dp[i+1] = dp[i-1] else: dp[i+1] += dp[i] if i > 0 and s[i-1] != '0' and int(s[i-1:i+1]) <= 26: dp[i+1] += dp[i-1] return dp[n] <file_sep>type RandomizedCollection struct { data []*int indexs map[int][]int unused []int len int cap int } func Constructor() RandomizedCollection { return RandomizedCollection{ data: make([]*int, 0), indexs: make(map[int][]int), unused: make([]int, 0), len: 0, cap: 0, } } func (this *RandomizedCollection) Insert(val int) bool { if this.len == this.cap { newData := make([]*int, this.cap*2+1) newCap := len(newData) k := 0 for i := 0; i < this.cap; i++ { if this.data[i] != nil { newData[k] = this.data[i] k++ } } this.data = newData this.cap = newCap } index := -1 if len(this.unused) > 0 { index = this.unused[len(this.unused)-1] this.unused = this.unused[:len(this.unused)-1] } else { index = this.len } this.data[index] = &val this.indexs[val] = append(this.indexs[val], index) this.len++ return len(this.indexs[val]) == 1 } func (this *RandomizedCollection) Remove(val int) bool { if len(this.indexs[val]) == 0 { return false } indexs := this.indexs[val] index := indexs[len(indexs)-1] indexs = indexs[:len(indexs)-1] if len(indexs) == 0 { delete(this.indexs, val) } else { this.indexs[val] = indexs } this.data[index] = nil this.unused = append(this.unused, index) this.len-- return true } func (this *RandomizedCollection) GetRandom() int { if this.len == 0 { return 0 } for { index := rand.Intn(this.cap) if this.data[index] != nil { return *this.data[index] } } } /** * Your RandomizedCollection object will be instantiated and called as such: * obj := Constructor(); * param_1 := obj.Insert(val); * param_2 := obj.Remove(val); * param_3 := obj.GetRandom(); */ <file_sep># @param {String} pattern # @param {String} str # @return {Boolean} def word_pattern(pattern, str) str = str.split(' ') h1 = {} h2 = {} return false if pattern.length != str.length for i in 0...str.length p =pattern[i] s = str[i] if h1[p].nil? && h2[s].nil? h1[p] = s h2[s]=p elsif h1[p] == s && h2[s] == p next else return false end end true end<file_sep>class Solution: def flipLights(self, n: int, m: int) -> int: if n == 0 or m == 0: return 1 if n == 1: return 2 if n == 2: if m == 1: return 3 else: return 4 if m == 1: return 4 if m == 2: return 7 return 8<file_sep># @param {Integer} n # @return {String} def convert_to_title(n) return n>0 ? (convert_to_title((n-1)/26) + ((n-1)%26+65).chr) : '' end <file_sep>class Solution: def numRescueBoats(self, people: List[int], limit: int) -> int: n = len(people) if n <= 1: return n people.sort() ret = 0 i, j = 0, n - 1 while i <= j: while j > i and people[i] + people[j] > limit: j -= 1 ret += 1 if j > i and people[i] + people[j] <= limit: j -= 1 ret += 1 i += 1 return ret <file_sep># @param {Integer[]} nums # @param {Integer} target # @return {Integer[][]} def four_sum(nums, target) ret = [] nums.sort! for i in 0..nums.length-4 if i > 0 and nums[i] == nums[i-1] then next end for j in i+1..nums.length-3 if j > i+1 and nums[j] == nums[j-1] then next end l, r = j + 1, nums.length - 1 while l < r sum = nums[i] + nums[j] + nums[l] + nums[r] if sum < target l += 1 elsif sum > target r -= 1 else ret << [nums[i], nums[j], nums[l], nums[r]] while l < r and nums[l] == nums[l + 1] do l += 1 end while l < r and nums[r] == nums[r - 1] do r -= 1 end l += 1; r -= 1 end end end end return ret end <file_sep>class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: bits = [0] + [1<<i for i in range(9)] rows = [0] * 9 cols = [0] * 9 grids = [[0] * 3 for i in range(3)] for i in range(9*9): x, y = i // 9, i % 9 digit = board[x][y] if digit == ".": continue digit = int(digit) bit = bits[digit] if rows[x] & bit > 0 or cols[y] & bit > 0 or grids[x//3][y//3] & bit > 0: return False rows[x] |= bit cols[y] |= bit grids[x//3][y//3] |= bit return True<file_sep># Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def diameterOfBinaryTree(self, root): """ :type root: TreeNode :rtype: int """ self.diameter = 0 self._getH(root) return self.diameter def _getH(self, node): if node is None: return 0 lh = self._getH(node.left) rh = self._getH(node.right) self.diameter = max(self.diameter, lh+rh) return max(lh, rh) + 1<file_sep>class Solution: def nextGreaterElement(self, n: int) -> int: def next_permutation(arr): n = len(arr) if n <= 1: return False i, j = n-2, n-1 while i >= 0 and arr[i] >= arr[j]: i -= 1 j -= 1 if i < 0: return False k = n - 1 while arr[i] >= arr[k]: k -= 1 arr[i], arr[k] = arr[k], arr[i] a, b = j, n-1 while a < b: arr[a], arr[b] = arr[b], arr[a] a += 1 b -= 1 return True digits = list(str(n)) if next_permutation(digits): greater = int(''.join(digits)) if greater <= (1 << 31)-1: return greater return -1<file_sep>class Solution: def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: res = [] n = len(arr) l, r = 0, n while l < r: m = (l + r) // 2 if x < arr[m]: r = m else: l = m + 1 l = r - 1 for i in range(k): if l < 0 or (r<n and abs(arr[l]-x) > abs(arr[r]-x)): res.append(arr[r]) r+=1 else: res.append(arr[l]) l -= 1 res.sort() return res <file_sep>class Solution: def lengthOfLongestSubstring(self, s: str) -> int: sub_len, k = 0, 0 sub = {} for i, c in enumerate(s): if c in sub: k = max(k, sub[c] + 1) sub[c] = i sub_len = max(sub_len, i-k+1) return sub_len<file_sep>class Solution: def superPow(self, a: int, b: List[int]) -> int: x = reduce(lambda x,y: x*10 + y, b, 0) def pow(k): if k == 0: return 1 if k == 1: return a % 1337 if k&1 == 1: y = pow(k//2) return y*y * a % 1337 y = pow(k//2) return y*y % 1337 return pow(x)<file_sep># Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]: r1, r2 = ListNode(), ListNode() h1, h2 = r1, r2 while head: if head.val < x: h1.next = head h1 = h1.next else: h2.next = head h2 = h2.next head = head.next h1.next = r2.next h2.next = None return r1.next <file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode: def buildMaxTree(nums, l, r): if l > r: return None m = l for i in range(l+1, r+1): if nums[i] > nums[m]: m = i node = TreeNode(nums[m]) node.left = buildMaxTree(nums, l, m-1) node.right = buildMaxTree(nums,m+1, r) return node return buildMaxTree(nums, 0, len(nums)-1)<file_sep>class Solution: def numberOfArithmeticSlices(self, nums: List[int]) -> int: n = len(nums) ret = 0 cnt = 0 for i in range(2, n): if nums[i-1] - nums[i-2] == nums[i] - nums[i-1]: cnt += 1 else: ret += (1+cnt) * cnt // 2 cnt = 0 ret += (1+cnt) * cnt // 2 return ret<file_sep>func findRightInterval(intervals [][]int) []int { n := len(intervals) res := make([]int, n) for i := 0; i < n; i++ { res[i] = -1 } index := make([]int, n) for i := 0; i < n; i++ { index[i] = i } less := func(i, j int) bool { return intervals[index[i]][0] < intervals[index[j]][0] } sort.Slice(index, less) for i := 0; i < n; i++ { l, r := 0, n for l < r { m := (l + r) / 2 if intervals[index[m]][0] < intervals[i][1] { l = m + 1 } else { r = m } } if l < n { res[i] = index[l] } } return res }<file_sep>class MinStack: def __init__(self): self._a = [] self._min = None def push(self, val: int) -> None: if len(self._a) == 0 or val < self._min: self._min = val self._a.append((val, self._min)) def pop(self) -> None: val, m = self._a.pop() if val == m: if len(self._a) == 0: self._min = None else: self._min = self._a[-1][1] return val def top(self) -> int: return self._a[-1][0] def getMin(self) -> int: return self._a[-1][1] # Your MinStack object will be instantiated and called as such: # obj = MinStack() # obj.push(val) # obj.pop() # param_3 = obj.top() # param_4 = obj.getMin()<file_sep>class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: from collections import defaultdict groups = defaultdict(list) for s in strs: groups[''.join(sorted(list(s)))].append(s) return list(groups.values()) <file_sep># Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseKGroup(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if k<=1 or not head: return head def walk(h): while h: x=h.next yield h h=x def reverse(h): t=None for x in walk(h): x.next=t t=x return t def add(h, t, v): if not h: h=t=v else: t.next=v t=v return [h, t] def printlist(h): for x in walk(h): print x.val, print '' c=1 h = t = head head = tail = None while t: if c % k == 0: x = t.next t.next = None #printlist( reverse(h) ) head, tail = add(head, tail, reverse(h)) #printlist( head ) tail = h h = x t = x c += 1 else: t = t.next c += 1 if h: head, tail = add(head, tail, h) return head <file_sep>func constructArray(n int, k int) []int { res := make([]int, n) res[0] = 1 j := 1 for i := 0; i < k; i++ { res[i+1] = res[i] + (k-i)*j j = -j } for i := k+1;i<n;i++ { res[i] = i+1 } return res }<file_sep>class Solution: def repeatedNTimes(self, A: 'List[int]') -> 'int': s = set() for e in A: if e in s: return e s.add(e)<file_sep>func findMinArrowShots(points [][]int) int { n := len(points) if n <= 1 { return n } sort.Slice(points, func(i, j int) bool { return points[i][1] < points[j][1] }) res := 1 right := points[0][1] for i := 1; i < n; i++ { if points[i][0] > right { res++ right = points[i][1] } else if points[i][1] < right { right = points[i][1] } } return res }<file_sep>class Solution: def findCircleNum(self, isConnected: List[List[int]]) -> int: n = len(isConnected) e = [[] for i in range(n)] for i in range(n): for j in range(n): if isConnected[i][j]: e[i].append(j) e[j].append(i) visited = [False] * n def dfs(i): if visited[i]: return visited[i] = True for j in e[i]: dfs(j) ret = 0 for i in range(n): if not visited[i]: ret += 1 dfs(i) return ret<file_sep>class Solution(object): def imageSmoother(self, M): """ :type M: List[List[int]] :rtype: List[List[int]] """ m = len(M) n = len(M[0]) def get(i, j): if i<0 or i>=m or j<0 or j>=n: return 0, 0 else: return 1, M[i][j] def avg(i, j): a, b = 0, 0 for x, y in [[0, 0], [-1, -1], [-1, 0], [-1, 1], [1, 1], [1, 0], [1, -1], [0, -1], [0, 1]]: q, w = get(i+x, j+y) a+=q b+=w return b/a ret = [[avg(i, j) for j in xrange(n)] for i in xrange(m)] return ret <file_sep>class Solution(object): def increasingTriplet(self, nums): """ :type nums: List[int] :rtype: bool """ if (not nums) or len(nums) < 3: return False ret = 1 x = nums[0] y = float('inf') for i in nums: if i < x: x = i elif i > x and i < y: y = i if i > y: return True return False <file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def pathSum(self, root: TreeNode, targetSum: int) -> int: from collections import defaultdict def path(node, sums): if not node: return 0 sums2 = defaultdict(int) sums2[node.val] = 1 for key, val in sums.items(): sums2[key+node.val] += val return sums2.get(targetSum, 0) + path(node.left, sums2.copy()) + path(node.right, sums2.copy()) return path(root, defaultdict(int)) <file_sep>class Solution: def maxSumDivThree(self, nums: List[int]) -> int: a, b = [0,0,0], [0,0,0] ret = 0 for num in nums: b = a[:] for x in a: y = num + x z = y % 3 b[z] = max(b[z], y) ret = max(ret, b[0]) a = b return ret<file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def recoverTree(self, root: Optional[TreeNode]) -> None: """ Do not return anything, modify root in-place instead. """ left, right = None, None n1, n2 = None, None q = [] node = root while node: q.append(node) node = node.left while len(q) > 0: node = q.pop() n1, n2 = n2, node if n1 and n1.val > n2.val: if not left: left, right = n1, n2 else: right = n2 left.val, right.val = right.val, left.val break node = node.right while node: q.append(node) node = node.left if left.val > right.val: left.val, right.val = right.val, left.val <file_sep>func searchMatrix(matrix [][]int, target int) bool { m, n := len(matrix), len(matrix[0]) x1, y1, x2, y2 := 0, 0, m-1, n-1 for x1 <= x2 && y1 <= y2 { if matrix[x1][y1] == target || matrix[x2][y2] == target || matrix[x1][y2] == target || matrix[x2][y1] == target { return true } if matrix[x1][y2] < target { x1++ } else { y2-- } if matrix[x2][y1] < target { y1++ } else { x2-- } } return false } <file_sep>class Solution: def isGoodArray(self, nums: List[int]) -> bool: def gcd(a, b): if a%b == 0: return b return gcd(b, a%b) g = nums[0] for num in nums: g = gcd(g, num) return g == 1<file_sep>""" # Definition for a Node. class Node: def __init__(self, val = 0, neighbors = None): self.val = val self.neighbors = neighbors if neighbors is not None else [] """ class Solution: def cloneGraph(self, node: 'Node') -> 'Node': if not node: return None root = node nodes = {node.val: node} newNodes = {node.val: Node(node.val)} q = [node] while len(q) > 0: node = q.pop() if not node.neighbors: continue for node in node.neighbors: if node.val not in nodes: nodes[node.val] = node newNodes[node.val] = Node(node.val) q.append(node) for node in nodes.values(): if not node.neighbors: continue newNode = newNodes[node.val] newNode.neighbors = [newNodes[neighbor.val] for neighbor in node.neighbors] return newNodes.get(root.val) <file_sep>class Solution: def longestConsecutive(self, nums: List[int]) -> int: ret = 0 left, right = 1, -1 nums_set = set(nums) def get_longest_seq(num): l, r = num, num while l - 1 in nums_set: l -= 1 nums_set.remove(l) while r + 1 in nums_set: r += 1 nums_set.remove(r) return l, r for num in nums: if left <= num and num <= right: continue l, r = get_longest_seq(num) if r - l + 1 > ret: ret = r - l + 1 left, right = l, r return ret<file_sep>class Solution: def get_max(self, g, m, n, x, y): if x < 0 or x >= m or y < 0 or y >= n or g[x][y] == 0: return 0 t = g[x][y] g[x][y] = 0 a = self.get_max(g, m, n, x+1, y) b = self.get_max(g, m, n, x-1, y) c = self.get_max(g, m, n, x, y+1) d = self.get_max(g, m, n, x, y-1) ret = max(a, b, c, d) + t g[x][y] = t return ret def getMaximumGold(self, grid: List[List[int]]) -> int: ret = 0 m, n = len(grid), len(grid[0]) for i in range(m): for j in range(n): if grid[i][j] > 0: ret = max(ret, self.get_max(grid, m, n, i, j)) return ret<file_sep>func totalNQueens(n int) int { res := 0 colVisited := make([]bool, n) leftVisited := make([]bool, 2*n-1) rightVisited := make([]bool, 2*n-1) var dfs func(row int) dfs = func(row int) { if row == n { res++ return } for col := 0; col < n; col++ { if !colVisited[col] && !leftVisited[row+col] && !rightVisited[row-col+n-1] { colVisited[col] = true leftVisited[row+col] = true rightVisited[row-col+n-1] = true dfs(row + 1) colVisited[col] = false leftVisited[row+col] = false rightVisited[row-col+n-1] = false } } } dfs(0) return res }<file_sep>class Solution: def romanToInt(self, s: str) -> int: ret = [] for c in s: if c == 'I': ret.append(1) elif c == 'V': ret.append(5) elif c == 'X': ret.append(10) elif c == 'L': ret.append(50) elif c == 'C': ret.append(100) elif c == 'D': ret.append(500) else: ret.append(1000) for i in range(len(ret)-1): if ret[i] < ret[i+1]: ret[i] = -ret[i] return sum(ret)<file_sep>class Solution(object): def minMutation(self, start, end, bank): """ :type start: str :type end: str :type bank: List[str] :rtype: int """ class Queue(object): def __init__(self): self.f = [] self.r = [] def push(self, x): self.f.append(x) def pop(self): if len(self.r) == 0: self.r = self.f self.r.reverse() self.f = [] return self.r.pop() def __len__(self): return len(self.f) + len(self.r) visited = set() q = Queue() q.push((start, 0)) visited.add(start) while len(q) > 0: x, s = q.pop() if x == end: return s s += 1 for i in range(8): for c in "ACGT": x2 = x[0:i] + c + x[i+1:] if (x2 in bank) and (x2 not in visited): visited.add(x2) q.push((x2, s)) return -1 <file_sep> class Solution(object): def findCircleNum(self, M): """ :type M: List[List[int]] :rtype: int """ if not M: return 0 n = len(M) p = [-1] * n ret = [n] def find(x): if p[x] == -1: return x else: y = find(p[x]) p[x] = y return y def union(a, b): x = find(a) y = find(b) if x != y: p[y] = x ret[0] -= 1 for i in xrange(n): for j in xrange(i, n): if M[i][j] == 1: union(i, j) return ret[0] <file_sep>class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ z0, z1, z2 = 0, 0, 0 for num in nums: if num == 0: z0 += 1 elif num == 1: z1 += 1 else: z2 += 1 i = 0 while z0 > 0: nums[i] = 0 z0 -= 1 i += 1 while z1 > 0: nums[i] = 1 z1 -= 1 i += 1 while z2 > 0: nums[i] = 2 z2 -= 1 i += 1 <file_sep>class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: candidates.sort() ret = [] q = [(0, 0, [])] while len(q) > 0: i, s, nums = q.pop() if s == target: ret.append(nums) continue if i >= len(candidates) or s + candidates[i] > target: continue q.append((i, s + candidates[i], nums+[candidates[i]])) q.append((i+1, s, nums)) return ret<file_sep>class Solution(object): def maxSlidingWindow(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ if not nums: return [] x = 1 q = [float('inf')] ret = [] for i in nums[:k]: while len(q) > x and i > q[-1]: q.pop() q.append(i) ret.append(q[x]) for idx, i in enumerate(nums[k:], k): if q[x] == nums[idx-k]: x += 1 while len(q) > x and i > q[-1]: q.pop() q.append(i) ret.append(q[x]) return ret<file_sep>class Solution: def exclusiveTime(self, n: int, logs: List[str]) -> List[int]: ret = [0] * n funcs = [] prev_time = -1 for log in logs: id, start, time = log.split(":") id, start, time = int(id), start=="start", int(time) if start: if len(funcs) > 0: ret[funcs[-1]] += time - prev_time funcs.append(id) else: time += 1 ret[id] += time - prev_time funcs.pop() prev_time = time return ret<file_sep>func countDigitOne(n int) int { res := 0 for i := 1; i <= n; i *= 10 { m := (n / i) % 10 if m == 0 { res += n / (i * 10) * i } else if m == 1 { res += n/(i*10)*i + n%i + 1 } else { res += (n/(i*10) + 1) * i } } return res } <file_sep>class Solution: def isIsomorphic(self, s: str, t: str) -> bool: n = len(s) m = {} m2 = {} for i in range(n): if s[i] in m: if m[s[i]] != t[i]: return False if t[i] in m2: if m2[t[i]] != s[i]: return False else: m[s[i]] = t[i] m2[t[i]] = s[i] return True <file_sep>class Solution: def convertToTitle(self, columnNumber: int) -> str: ret = '' num = columnNumber while num > 0: num -= 1 ret = chr(ord('A') + (num % 26)) + ret num //= 26 return ret<file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def constructFromPrePost(self, pre: List[int], post: List[int]) -> TreeNode: index = {} lenp = len(post) for i in range(lenp): index[post[i]] = i def construct(pre, a, b, post, l, r): if a > b: return None root = TreeNode(pre[a]) if a + 1 <= b: i = index[pre[a+1]] x = i - l root.left = construct(pre, a+1, a+1+x, post, l, l + x) root.right = construct(pre, a+1+x+1, b, post, l+x+1, r) return root return construct(pre, 0, lenp-1, post, 0, lenp-1) <file_sep>class MedianFinder { public: /** initialize your data structure here. */ MedianFinder():n(0) { } void addNum(int num) { if(n&1) r.push(num); else l.push(num); if (n++ > 1) { while (l.top() > r.top()) { int a = l.top(), b = r.top(); l.pop(); r.pop(); l.push(b); r.push(a); } } } double findMedian() { if (n&1) return (double)l.top(); else return (l.top() + r.top()) / 2.0; } private: priority_queue<int, vector<int>, greater<int>> r; priority_queue<int, vector<int>, less<int>>l; int n; }; /** * Your MedianFinder object will be instantiated and called as such: * MedianFinder obj = new MedianFinder(); * obj.addNum(num); * double param_2 = obj.findMedian(); */<file_sep>class Solution { public: string reverseStr(string s, int k) { for(int i=0;i*k < s.length(); i+=2) reverse(s.begin()+k*i, min(s.begin()+k*i+k, s.end()) ); return s; } };<file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def rob(self, root: TreeNode) -> int: d1 = {} d2 = {} def dp(node, rob_parent): if not node: return 0 if rob_parent: if node in d1: return d1[node] a = dp(node.left, False) + dp(node.right, False) d1[node] = a return a else: if node in d1: a = d1[node] else: a = dp(node.left, False) + dp(node.right, False) if node in d2: b = d2[node] else: b = node.val + dp(node.left, True) + dp(node.right, True) return max(a, b) return dp(root, False)<file_sep>class Solution: def reachNumber(self, target: int) -> int: if target < 0: target = -target ret = 1 s = 0 while True: s += ret if s == target or (s > target and (s-target)%2==0): return ret ret += 1<file_sep>class Solution(object): def carPooling(self, trips, capacity): """ :type trips: List[List[int]] :type capacity: int :rtype: bool """ def cmp(a, b): if a[2] == b[2]: return -(a[0] - b[0]) return a[2] - b[2] ts = [] for t in trips: ts.append((0, t[0], t[1])) ts.append((1, t[0], t[2])) ts.sort(cmp=cmp) print(ts) for t in ts: if t[0] == 0: capacity -= t[1] if capacity < 0: return False else: capacity += t[1] return True <file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def distanceK(self, root, target, K): """ :type root: TreeNode :type target: TreeNode :type K: int :rtype: List[int] """ f = {} q = [root] while len(q) > 0: r = q.pop() if r.left: f[r.left] = r q.append(r.left) if r.right: f[r.right] = r q.append(r.right) q = [target] visited = set() visited.add(target) visited.add(None) while K > 0 and len(q) > 0: K -= 1 q2 = [] for node in q: if node.left not in visited: q2.append(node.left) visited.add(node.left) if node.right not in visited: q2.append(node.right) visited.add(node.right) if f.get(node, None) not in visited: q2.append(f[node]) visited.add(f[node]) q = q2 return [node.val for node in q] <file_sep>class Solution: def largestDivisibleSubset(self, nums: List[int]) -> List[int]: n = len(nums) if n <= 1: return nums nums.sort() ret = [1] * n last = [-1] * n for i in range(n): for j in range(i+1, n): if ret[i] < ret[j] or nums[j] % nums[i] != 0: continue ret[j] = ret[i] + 1 last[j] = i i = ret.index(max(ret)) r = [] while i >= 0: r.append(nums[i]) i = last[i] #r.sort() return r <file_sep>class Solution(object): def repeatedSubstringPattern(self, s): """ :type s: str :rtype: bool """ def check(s, n, k): for i in xrange(k, n, k): if s[:k] != s[i:i+k]: return False return True import math n = len(s) if n>1 and check(s, n, 1): return True vi = [True] * (n+1) for i in xrange(2, n/2+1): if vi[i] and n%i == 0: if check(s, n, n/i): return True else: for j in xrange(i, n, i): vi[j]=False return False <file_sep>class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: letters = {} for c in magazine: if c in letters: letters[c] += 1 else: letters[c] = 1 for c in ransomNote: if letters.get(c, 0) == 0: return False else: letters[c] -= 1 return True<file_sep>class Solution: def triangleNumber(self, nums: List[int]) -> int: nums.sort() ret = 0 n = len(nums) def upper_bound(l, r, x): while l < r: m = (l + r) // 2 if nums[m] <= x: l = m + 1 else: r = m return l def lower_bound(l, r, x): while l < r: m = (l + r) // 2 if nums[m] < x: l = m + 1 else: r = m return l for i in range(n): for j in range(i+1, n): ret += lower_bound(j+1, n, nums[i]+nums[j]) - (j+1) return ret<file_sep>class Solution(object): def minPathSum(self, grid): """ :type grid: List[List[int]] :rtype: int """ m, n = len(grid), len(grid[0]) get = lambda x, y: float('inf') if x<0 or y<0 else grid[x][y] for i in range(m): for j in range(n): if i==0 and j==0:continue grid[i][j] += min(get(i-1, j), get(i, j-1)) return grid[-1][-1] <file_sep>class Solution(object): def asteroidCollision(self, asteroids): """ :type asteroids: List[int] :rtype: List[int] """ ret = [] for a in asteroids: if len(ret) == 0 or a > 0 or ret[-1] < 0: ret.append(a) else: while len(ret) > 0 and ret[-1] > 0 and abs(a) > ret[-1]: ret.pop() if len(ret) > 0 and ret[-1] == abs(a): ret.pop() elif len(ret) == 0 or ret[-1] < 0: ret.append(a) return ret<file_sep>class Solution: def licenseKeyFormatting(self, s: str, k: int) -> str: s = s.replace("-", "").upper() n = len(s) m = n % k res = [] if m > 0: res.append(s[:m]) i=m while i < n: res.append(s[i:i+k]) i+=k return "-".join(res) <file_sep># Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def numComponents(self, head: Optional[ListNode], nums: List[int]) -> int: nums = set(nums) nums2 = set() nodes = {} h = head while h: nodes[h.val] = h h = h.next h = head ret = 0 while h: num = h.val h = h.next if (num not in nums) or (num in nums2): continue ret += 1 node = nodes[num] while node and node.val in nums: nums2.add(node.val) node = node.next return ret <file_sep>class Solution: def searchRange(self, nums: List[int], target: int) -> List[int]: if len(nums) == 0: return [-1, -1] def lower_bound(l, r): while l <= r: m = (l + r) >> 1 if nums[m] < target: l = m + 1 else: r = m - 1 return l def upper_bound(l, r): while l <= r: m = (l + r) >> 1 if nums[m] <= target: l = m + 1 else: r = m - 1 return l l = lower_bound(0, len(nums)-1) if l < len(nums) and nums[l] == target: return [l, upper_bound(l, len(nums)-1)-1] return [-1, -1]<file_sep>class RandomizedCollection { public: /** Initialize your data structure here. */ RandomizedCollection() : generator(time(0)), distribution(0, 0x7fffffff) { size = getExpandSize(); data = new int[size]; has = new char[size]; used = 0; for (int i = 0; i<size; ++i)has[i] = 0; } /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */ bool insert(int val) { if (size * 0.7 < used + 1) expand(); bool ret = true; bool inserted = false; for (unsigned h = hash(val); ; h = (h + 1) % size) { if (has[h] <= 1) { int oldh = has[h]; if (!inserted) { has[h] = 2; used++; data[h] = val; inserted = true; } if (oldh == 0) { break; } } else //(has[h] == 2) { if (data[h] == val) { ret = false; } } } return ret; } /** Removes a value from the collection. Returns true if the collection contained the specified element. */ bool remove(int val) { for (unsigned h = hash(val); ; h = (h + 1) % size) { if (has[h] == 2) { if (data[h] == val) { has[h] = 1; //used --; return true; } } else if (has[h] == 0) { return false; } } return false; } /** Get a random element from the collection. */ int getRandom() { while (1) { unsigned h = (unsigned)distribution(generator) % size; while (has[h] != 2) { h = (unsigned)distribution(generator) % size; } return data[h]; } return 0; } protected: unsigned getExpandSize(unsigned curSize = 0) { static vector<unsigned> primes = { 11, 23, 53, 97, 193, 389, 769, 1543, 3079, 6151, 12289, 24593, 49157, 98317, 196613, 393241, 786433, 1572869, 3145739, 6291469, 12582917, 25165843, 50331653, 100663319, 201326611 }; auto it = upper_bound(primes.begin(), primes.end(), curSize); if (it == primes.end()) return *(it - 1); else return *it; } unsigned hash(int val) { return val%size; } void expand() { used = 0; unsigned newsize = getExpandSize(size); int *newdata = new int[newsize]; char *newhas = new char[newsize]; for (int i = 0; i<newsize; ++i)newhas[i] = 0; for (unsigned i = 0; i < size; ++i) { if (has[i] == 2) { used++; for (unsigned h = (unsigned)data[i] % newsize; ; h = (h + 1) % newsize) { if (newhas[h] <= 1) { newhas[h] = 2; newdata[h] = data[i]; break; } } } } swap(size, newsize); swap(data, newdata); swap(has, newhas); delete newdata; delete newhas; } int *data; unsigned size; unsigned used; char *has; default_random_engine generator; uniform_int_distribution<int> distribution; };<file_sep>class Solution: def maxChunksToSorted(self, arr: List[int]) -> int: ret = 0 n = len(arr) i = 0 while i < n: l = arr[i] r = arr[i] j = i while j < n: l = min(l, arr[j]) r = max(r, arr[j]) if l == i and r == j: j += 1 break j += 1 i = j ret += 1 return ret<file_sep>class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: n = len(nums) sum = 0 i, j = 0, 0 ret = n + 1 while i < j or j < n: if sum < target: if j < n: sum += nums[j] j += 1 else: break else: ret = min(ret, j - i) sum -= nums[i] i += 1 if ret <= n: return ret return 0 <file_sep>class Que: def __init__(self): self.a = [] self.b = [] def push(self, x): self.b.append(x) def pop(self): if len(self.a) == 0: self.a = self.b self.a.reverse() self.b = [] return self.a.pop() def size(self): return len(self.a) + len(self.b) class Solution: def shortestBridge(self, A: List[List[int]]) -> int: def get_island(A, x, y, z): m, n = len(A), len(A[0]) island = set() island.add((x, y)) q = [(x, y)] A[x][y] = z while len(q) > 0: a, b = q.pop() if a + 1 < m and A[a+1][b] == 1 and (a+1, b) not in island: island.add((a+1, b)) q.append((a+1, b)) A[a+1][b] = z if a - 1 >= 0 and A[a-1][b] == 1 and (a-1, b) not in island: island.add((a-1, b)) q.append((a-1, b)) A[a-1][b] = z if b + 1 < n and A[a][b+1] == 1 and (a, b+1) not in island: island.add((a, b+1)) q.append((a, b+1)) A[a][b+1] = z if b - 1 >= 0 and A[a][b-1] == 1 and (a, b-1) not in island: island.add((a, b-1)) q.append((a, b - 1)) A[a][b-1] = z return island def get_bridge(A, x, y, z, ret, bridge): m, n = len(A), len(A[0]) q = Que() q.push((x, y, 0)) dx = [[1, 0], [-1, 0], [0, 1], [0, -1]] while q.size() > 0: a, b, s = q.pop() if s - 1 > ret: return ret if A[a][b] == z: return s - 1 for d in dx: x2 = a + d[0] y2 = b + d[1] if x2 >= 0 and x2 < m and y2 >= 0 and y2 < n and A[x2][y2] in (0, z) and (bridge[x2][y2] == -1 or s + 1 < bridge[x2][y2]): bridge[x2][y2] = s + 1 q.push((x2, y2, s+1)) return float('inf') m, n = len(A), len(A[0]) lands = [] for i in range(m): for j in range(n): if A[i][j] == 1 and (len(lands) == 0 or (i, j) not in lands[0]): land = get_island(A, i, j, len(lands)+1) lands.append(land) if len(lands) == 2: break if len(lands[0]) > len(lands[1]): lands[0], lands[1] = lands[1], lands[0] bridge = [[-1 for i in range(n)] for j in range(m)] ret = float('inf') for x, y in lands[0]: z = 1 if A[x][y] == 1: z = 2 ret = min(ret, get_bridge(A, x, y, z, ret, bridge)) return ret <file_sep>class Solution(object): def firstMissingPositive(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 1 n = len(nums) i = 0 ret = n+1 while i < n: e = nums[i] if i+1 != e and 1<= e <= n and nums[e-1] != e: nums[i], nums[e-1] = nums[e-1], e else: i += 1 for i, e in enumerate(nums): if i+1 != e: return i+1 return ret <file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]: def bst(node, val): retVal = node.val node.val += val if node.right: x = bst(node.right, val) retVal += x node.val += x if node.left: retVal += bst(node.left, node.val) return retVal if root: bst(root, 0) return root<file_sep>/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func findMode(root *TreeNode) []int { res := []int{} val, count, maxCount := 0, 0, 0 var find func(node *TreeNode) find = func(node *TreeNode) { if node == nil { return } find(node.Left) if node.Val == val { count++ } else { val = node.Val count = 1 } if count == maxCount { res = append(res, val) } else if count > maxCount { maxCount = count res = []int{val} } find(node.Right) } find(root) return res }<file_sep>class Solution: def isPerfectSquare(self, num: int) -> bool: l, r = 0, num while l <= r: m = (l + r) // 2 x = m * m if x < num: l = m + 1 elif x > num: r = m - 1 else: return True return False<file_sep>class Solution: def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]: ret = [] lenp = len(pattern) for word in words: if len(word) == lenp: d = {} d2 = {} for i in range(lenp + 1): if i == lenp: ret.append(word) break if word[i] in d: w = d[word[i]] else: w = d[word[i]] = pattern[i] if pattern[i] in d2: w2 = d2[pattern[i]] else: w2 = d2[pattern[i]] = word[i] if w != pattern[i] or w2 != word[i]: break return ret<file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def bstToGst(self, root: TreeNode) -> TreeNode: def visit(ro, val): if ro is None: return val val = visit(ro.right, val) ro.val += val return visit(ro.left, ro.val) visit(root, 0) return root<file_sep># Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def sortList(self, head: ListNode) -> ListNode: if (not head) or (not head.next): return head a, b = head, head.next while b and b.next: a, b = a.next, b.next.next b = a.next a.next = None a = head a, b = self.sortList(a), self.sortList(b) root = ListNode(0) tail = root while a and b: if a.val <= b.val: tail.next = a a = a.next else: tail.next = b b = b.next tail = tail.next while a: tail.next = a a = a.next tail = tail.next while b: tail.next = b b = b.next tail = tail.next return root.next <file_sep>class Solution: def uniquePaths(self, m: int, n: int) -> int: paths = [[0 for j in range(n)] for i in range(m)] paths[0][0] = 1 for i in range(m): for j in range(n): if i-1 >= 0: paths[i][j] += paths[i-1][j] if j-1 >= 0: paths[i][j] += paths[i][j-1] return paths[m-1][n-1]<file_sep>class Solution(object): def findDisappearedNumbers(self, nums): """ :type nums: List[int] :rtype: List[int] """ ret = [] n = len(nums) i = 0 while i < n: v = nums[i] if nums[v-1] != v: nums[v-1], nums[i] = v, nums[v-1] else: i+=1 #print nums for i in range(n): if i+1 != nums[i]: ret.append(i+1) return ret<file_sep>class Solution(object): def queensAttacktheKing(self, queens, king): """ :type queens: List[List[int]] :type king: List[int] :rtype: List[List[int]] """ board = [[False]*8 for i in range(8)] for r, c in queens: board[r][c] = True ret = [] a, b = king[0], king[1] d = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]] for x, y in d: for i in range(1, 8): r = a + x*i c = b + y*i if r < 0 or r > 7 or c < 0 or c > 7: break if board[r][c]: ret.append([r,c]) break return ret<file_sep>class Solution: def diffWaysToCompute(self, expression: str) -> List[int]: n = len(expression) if n == 0: return [] dp = [[[] for _ in range(n+1)] for _ in range(n+1)] def dfs(l, r): if len(dp[l][r]) > 0: return if expression[l:r].isdigit(): dp[l][r].append(int(expression[l:r])) return for i in range(l, r): if expression[i] in "+-*": dfs(l, i) dfs(i+1, r) for x in dp[l][i]: for y in dp[i+1][r]: if expression[i] == "+": dp[l][r].append(x+y) elif expression[i] == "-": dp[l][r].append(x-y) else: dp[l][r].append(x*y) dfs(0, n) return list(dp[0][n]) <file_sep>class Solution(object): def combinationSum3(self, k, n): """ :type k: int :type n: int :rtype: List[List[int]] """ self.ret = [] self._dfs(n, 9, k, []) return self.ret def _dfs(self, n, d, k, l): if k == 0 and n == 0: self.ret.append(l[:]) return if n <= 0 or d == 0 or k == 0: return self._dfs(n, d-1, k, l) l.append(d) self._dfs(n-d, d-1, k-1, l) l.pop() <file_sep>class Solution: def numFactoredBinaryTrees(self, A: List[int]) -> int: mod = 1000000000 + 7 A.sort() n = len(A) d = {} x = {} for i in A: d[i] = 1 for i in range(n): for j in range(i, n): p = A[i] * A[j] if p in d: if p in x: x[p].append((A[i], A[j])) else: x[p] = [(A[i], A[j])] for i in A: for a,b in x.get(i, []): c = d[a] * d[b] if a != b: c *= 2 d[i] = (d[i] + c) % mod return sum(d.values()) % mod <file_sep>class Solution: def removeComments(self, source): """ :type source: List[str] :rtype: List[str] """ ret = [] code = '\n'.join(source) n = len(code) i = 0 while i < n: if i+1 < n and code[i] == '/' and code[i+1] == '/': i += 2 while i < n and code[i] != '\n': i += 1 elif i+1 < n and code[i] == '/' and code[i+1] == '*': i += 2 while i+1 < n and not (code[i] == '*' and code[i+1] == '/'): i += 1 i += 2 else: ret.append(code[i]) i += 1 ret = ''.join(ret) print(ret) ret = ret.split('\n') ret2 = [] for line in ret: if line != '' and line != '\n' : ret2.append(line) return ret2<file_sep>class Solution: def getHint(self, secret: str, guess: str) -> str: from collections import defaultdict n = len(secret) a, b = 0, 0 s, g = defaultdict(int), defaultdict(int) for i in range(n): if secret[i] == guess[i]: a += 1 else: s[secret[i]] += 1 g[guess[i]] += 1 for key in g: if key in s: b += min(s[key], g[key]) return f'{a}A{b}B'<file_sep>class Solution: def findDuplicates(self, nums: List[int]) -> List[int]: ret = [] for i in range(len(nums)): while nums[i] != 0 and i+1 != nums[i]: num = nums[i] if nums[i] == nums[num-1]: ret.append(num) nums[i] = 0 break nums[i], nums[num-1] = nums[num-1], nums[i] return ret <file_sep>func isMatch(s string, p string) bool { m, n := len(s), len(p) f := make([][]bool, m+1) for i := 0; i < m+1; i++ { f[i] = make([]bool, n+1) } f[0][0] = true for j := 0; j < n; j++ { if p[j] == '*' { f[0][j+1] = f[0][j-1] } for i := 0; i < m; i++ { if s[i] == p[j] || p[j] == '.' { f[i+1][j+1] = f[i][j] } else if p[j] == '*' { if s[i] == p[j-1] || p[j-1] == '.' { f[i+1][j+1] = f[i+1][j] || f[i][j+1] } f[i+1][j+1] = f[i+1][j+1] || f[i+1][j-1] } } } return f[m][n] }<file_sep>class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ if not s: return '' n = len(s) n2 = (n << 1) | 1 p = [1] * n2 x = [1, 0] for c in s: x.append(c) x.append(0) x.append(2) i, id, mx, id2, mx2 = 1, 0, 0, 0, 0 for i in range(1, n2): if mx > i: p[i] = min(p[2 * id - i], mx - i) while x[i - p[i]] == x[i + p[i]]: p[i] += 1 if i + p[i] > mx: mx = i + p[i] id = i if p[i] > mx2: mx2 = p[i] id2 = i ret = [] for c in xrange(id2 - mx2 + 1, id2 + mx2): if x[c] != 0: ret.append(x[c]) return ''.join(ret) <file_sep>func circularArrayLoop(nums []int) bool { n := len(nums) if n < 2 { return false } next := func(index int) int { return ((index+nums[index])%n + n) % n } for i := 0; i < n; i++ { if nums[i] == 0 { continue } slow, fast := i, next(i) if slow == fast { nums[i] = 0 continue } for nums[slow]*nums[fast] > 0 && nums[slow]*nums[next(fast)] > 0 { if slow == fast { if slow == next(slow) { break } return true } slow = next(slow) fast = next(next(fast)) } for j := i; nums[j] != 0 && ((nums[j] < 0) == (nums[i] < 0)); j = next(j) { nums[j] = 0 } } return false } <file_sep>class Solution: def advantageCount(self, A: List[int], B: List[int]) -> List[int]: n = len(A) A.sort() b = [[B[i], i, None] for i in range(n)] b.sort(key=lambda x: x[0]) i = 0 a = [] for j in range(n): while i < n and A[i] <= b[j][0]: a.append(A[i]) i += 1 if i < n: b[j][2] = A[i] i += 1 a.reverse() for i in range(n): if b[i][2] is None: b[i][2] = a.pop() b.sort(key=lambda x: x[1]) return [b[i][2] for i in range(n)] <file_sep> func searchMatrix(matrix [][]int, target int) bool { m, n := len(matrix), len(matrix[0]) l, r := 0, m for l < r { mid := (l + r) / 2 if matrix[mid][n-1] == target { return true } if matrix[mid][n-1] < target { l = mid + 1 } else { r = mid } } if l == m { return false } row := l l, r = 0, n for l < r { mid := (l + r) / 2 if matrix[row][mid] == target { return true } if matrix[row][mid] < target { l = mid + 1 } else { r = mid } } return false } <file_sep># Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: l3 = ListNode(0) l3_head = l3 l0_value = 0 while l1 or l2: l1_value, l2_value = 0, 0 if l1: l1_value = l1.val l1 = l1.next if l2: l2_value = l2.val l2 = l2.next l3_value = (l0_value + l1_value + l2_value) % 10 l0_value = (l0_value + l1_value + l2_value) // 10 l3.next = ListNode(l3_value) l3 = l3.next if l0_value > 0: l3.next = ListNode(l0_value) return l3_head.next<file_sep># Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def allPossibleFBT(self, N): """ :type N: int :rtype: List[TreeNode] """ #from copy import deepcopy if N % 2 == 0: return [] dp = [[] for i in range(N + 1)] dp[1] = [TreeNode(0)] for i in range(3, N + 1): for j in range(1, i, 2): for left in dp[j]: for right in dp[i - 1 - j]: root = TreeNode(0) root.left = left root.right = right dp[i].append(root) return dp[N] <file_sep>class MyQueue: def __init__(self): self._s1 = [] self._s2 = [] def _getq(self): if len(self._s1) == 0: self._s1, self._s2 = self._s2, self._s1 self._s1.reverse() def push(self, x: int) -> None: self._s2.append(x) def pop(self) -> int: self._getq() return self._s1.pop() def peek(self) -> int: self._getq() return self._s1[-1] def empty(self) -> bool: return len(self._s1) == 0 and len(self._s2) == 0 # Your MyQueue object will be instantiated and called as such: # obj = MyQueue() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.peek() # param_4 = obj.empty()<file_sep>from heapq import heappush, heappop class Solution: def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]: if (not nums1) or (not nums2): return [] ret = [] for a in nums1: for b in nums2: heappush(ret, (-(a+b), (a, b))) if len(ret) > k: heappop(ret) ret = [i[1] for i in ret] return ret<file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def pathSum(self, root: TreeNode, targetSum: int) -> List[List[int]]: ret = [] q = [] if root: q = [[root.val, root, [root.val]]] while len(q) > 0: q2 = [] for sum, node, path in q: if (sum == targetSum) and (not node.left) and (not node.right): ret.append(path) else: if node.left: q2.append([sum+node.left.val, node.left, path[:] + [node.left.val]]) if node.right: path.append(node.right.val) q2.append([sum+node.right.val, node.right, path]) q = q2 return ret<file_sep>class Solution(object): def findMaxForm(self, strs, m, n): """ :type strs: List[str] :type m: int :type n: int :rtype: int """ dp = [[0] * (n + 1) for i in xrange(m + 1)] for s in strs: z0 = sum(1 for c in s if c == '0') z1 = sum(1 for c in s if c == '1') for x in xrange(m, -1, -1): for y in xrange(n, -1, -1): if x >= z0 and y >= z1: dp[x][y] = max(dp[x][y], dp[x - z0][y - z1] + 1) return dp[m][n] <file_sep>class Solution: def numberOfBoomerangs(self, points: List[List[int]]) -> int: n = len(points) d = [{} for i in range(n)] for i in range(n): for j in range(i+1, n): x = (points[i][0] - points[j][0])**2 + (points[i][1] - points[j][1])**2 d[i][x] = d[i].get(x, 0) + 1 d[j][x] = d[j].get(x, 0) + 1 ret = 0 for i in range(n): for x in d[i].values(): ret += x * (x - 1) return ret <file_sep># Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution(object): def findRightInterval(self, intervals): """ :type intervals: List[Interval] :rtype: List[int] """ def cmp(a, b): if a.start != b.start: return a.start-b.start return a.end-b.end def lower_bound(s, l, r, v): x=-1 while l<=r: m = (l+r)/2 if intervals[s[m]].start>=v: r = m-1 x=m else: l=m+1 if x !=-1: x = s[x] return x n = len(intervals) st = range(n) st.sort(key=lambda x: intervals[x], cmp=cmp) ret = [-1] * n for i in xrange(n): ret[st[i]] = lower_bound(st, 0, n-1, intervals[st[i]].end) return ret <file_sep>class Solution: def minRemoveToMakeValid(self, s: str) -> str: l, r = 0, 0 q = [] for c in s: if c == '(': l += 1 elif c == ')': r += 1 if r > l: r = l continue q.append(c) s = q s.reverse() q = [] l, r = 0, 0 for c in s: if c == '(': l += 1 elif c == ')': r += 1 if l > r: l = r continue q.append(c) q.reverse() return ''.join(q)<file_sep>class Solution: def longestArithSeqLength(self, A: List[int]) -> int: n = len(A) dp = [{} for i in range(n)] ret = 0 for i in range(0, n): for j in range(i+1, n): x = A[j] - A[i] y = max(dp[j].get(x, 1), dp[i].get(x, 1) + 1) ret = max(ret, y) dp[j][x] = y return ret<file_sep>func countBits(n int) []int { countBit := func(n int) int { res := 0 for n > 0 { res++ n &= n - 1 } return res } res := make([]int, n+1) for i := 0; i <= n; i++ { res[i] = countBit(i) } return res }<file_sep>func longestIncreasingPath(matrix [][]int) int { ret := 0 m, n := len(matrix), len(matrix[0]) dp := make([][]int, m) for i := range dp { dp[i] = make([]int, n) } max := func(a, b int) int { if a < b { return b } return a } var dfs func(i, j, k, num int) dfs = func(i, j, k, num int) { if i < 0 || i >= m || j < 0 || j >= n || matrix[i][j] <= num || k <= dp[i][j] { return } ret = max(ret, k) dp[i][j] = k dfs(i+1, j, k+1, matrix[i][j]) dfs(i-1, j, k+1, matrix[i][j]) dfs(i, j+1, k+1, matrix[i][j]) dfs(i, j-1, k+1, matrix[i][j]) } for i := 0; i < m; i++ { for j := 0; j < n; j++ { dfs(i, j, 1, -1) } } return ret }<file_sep>func findSubstring(s string, words []string) []int { res := make([]int, 0) n := len(s) wn, wl := len(words), len(words[0]) if n < wn*wl { return res } // words map nWorld := 0 wm := make(map[string]int) for _, w := range words { if wm[w] == 0 { nWorld++ } wm[w]++ } // sliding window for i := 0; i < wl; i++ { // reset start := i wm2 := make(map[string]int) nWorld2 := 0 for j := i; j+wl <= n; j += wl { w := s[j : j+wl] if wm[w] == 0 { start = j + wl wm2 = make(map[string]int) nWorld2 = 0 } else { wm2[w]++ if wm2[w] == wm[w] { nWorld2++ } else { for wm2[w] > wm[w] { w2 := s[start : start+wl] if wm2[w2] == wm[w2] { nWorld2-- } wm2[w2]-- start += wl } } if nWorld2 == nWorld { res = append(res, start) } } } } return res }<file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def sumNumbers(self, root: TreeNode) -> int: def sum(root, val): if not root: return 0 val = val * 10 + root.val if (not root.left) and (not root.right): return val return sum(root.left, val) + sum(root.right, val) return sum(root, 0)<file_sep>class Solution: def maxProduct(self, words: List[str]) -> int: n = len(words) chars = [0] * n orda = ord('a') for i in range(n): for c in words[i]: chars[i] = chars[i] | (1<<(ord(c) - orda)) ret = 0 for i in range(n): for j in range(i+1, n): if chars[i] & chars[j] > 0: continue ret = max(ret, len(words[i]) * len(words[j])) return ret<file_sep>class Solution: def findNumberOfLIS(self, nums: List[int]) -> int: n = len(nums) count = [1] *(n + 1) count[-1] = 0 length = [1] *(n+1) length[-1] = 0 for i in range(n): for j in range(i): if nums[j] >= nums[i]: continue if length[j] + 1 == length[i]: count[i] += count[j] elif length[j] + 1 > length[i]: length[i] = length[j] + 1 count[i] = count[j] #print(length) #print(count) max_length = max(length) ret = 0 for i in range(n): if length[i] == max_length: ret += count[i] return ret <file_sep>from functools import cmp_to_key class Solution: def removeCoveredIntervals(self, intervals: List[List[int]]) -> int: def cmp(a, b): if a[0] == b[0]: return b[1] - a[1] return a[0] - b[0] intervals.sort(key=cmp_to_key(cmp)) ret = 1 maxb = intervals[0][1] for interval in intervals: if interval[1] <= maxb: continue else: maxb = interval[1] ret+=1 return ret <file_sep>class Solution: def frequencySort(self, s: str) -> str: from collections import defaultdict frequency = defaultdict(int) for c in s: frequency[c] += 1 keys = list(frequency.keys()) keys.sort(key=lambda x: frequency[x], reverse=True) keys = [k*frequency[k] for k in keys] return ''.join(keys)<file_sep>func fullJustify(words []string, maxWidth int) []string { res := []string{} i, j := 0, 0 for i = 0; i < len(words); i = j { width := 0 for j = i; j < len(words) && width+len(words[j]) <= maxWidth; j++ { width += len(words[j]) + 1 } n := j - i line := "" if n == 1 { line = words[i] + strings.Repeat(" ", maxWidth-len(words[i])) } else if j < len(words) { spaces := maxWidth - width + n space := spaces / (n - 1) extra := spaces % (n - 1) for k := i; k < j; k++ { line += words[k] if k < j-1 { line += strings.Repeat(" ", space) if k-i < extra { line += " " } } } } else { for k := i; k < j; k++ { line += words[k] if k < j-1 { line += " " } } line += strings.Repeat(" ", maxWidth-len(line)) } res = append(res, line) } return res } <file_sep># Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: a, b, c, d= headA, headB, headA, headB while a and b: a, b = a.next, b.next while a: a, c = a.next, c.next while b: b, d = b.next, d.next while c and d: if c == d: return c c, d = c.next, d.next return None <file_sep># Read from the file file.txt and output all valid phone numbers to stdout. grep -P '^(\d{3}-\d{3}-\d{4})$|^(\(\d{3}\) \d{3}-\d{4})$' file.txt<file_sep>class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: n = len(strs) if n == 1: return strs[0] i, j = 0, 0 while True: for k in range(n-1): if len(strs[k]) <= j or len(strs[k+1]) <= j or strs[k][j] != strs[k+1][j]: return strs[0][i:j] j += 1 return strs[0][i:j] <file_sep>func ladderLength(beginWord string, endWord string, wordList []string) int { diff1 := func(a, b string) bool { diff := 0 for i := 0; i < len(a); i++ { if a[i] != b[i] { diff++ if diff > 1 { return false } } } return diff == 1 } endWorldExist := false wordList = append(wordList, beginWord) adjWorlds := make(map[string][]string) for i := 0; i < len(wordList); i++ { if wordList[i] == endWord { endWorldExist = true } for j := i + 1; j < len(wordList); j++ { if diff1(wordList[i], wordList[j]) { adjWorlds[wordList[i]] = append(adjWorlds[wordList[i]], wordList[j]) adjWorlds[wordList[j]] = append(adjWorlds[wordList[j]], wordList[i]) } } } if !endWorldExist { return 0 } visited := make(map[string]bool) queue := make([]string, 0) queue = append(queue, beginWord) visited[beginWord] = true step := 1 for len(queue) > 0 { queue2 := make([]string, 0) for _, world := range queue { if world == endWord { return step } for _, adj := range adjWorlds[world] { if !visited[adj] { queue2 = append(queue2, adj) visited[adj] = true } } } step++ queue = queue2 } return 0 }<file_sep>""" # Definition for a Node. class Node: def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): self.val = int(x) self.next = next self.random = random """ class Solution: def copyRandomList(self, head: 'Node') -> 'Node': root = Node(0) r = root h = head newNodes = {} while h: r.next = Node(h.val) newNodes[h] = r.next r = r.next h = h.next r = root.next h = head while h: if h.random: r.random = newNodes[h.random] h = h.next r = r.next return root.next<file_sep>func myAtoi(s string) int { res := int64(0) sign := 1 n := len(s) i := 0 // skip leading spaces for i < n && s[i] == ' ' { i++ } // check sign if i < n && s[i] == '+' { i++ } else if i < n && s[i] == '-' { sign = -1 i++ } // convert number and avoid overflow for i < n && s[i] >= '0' && s[i] <= '9' { res = res*10 + int64(s[i]-'0') if sign == 1 && res > math.MaxInt32 { return math.MaxInt32 } else if sign == -1 && res > int64(math.MaxInt32)+1 { return math.MinInt32 } i++ } return sign * int(res) }<file_sep>class Solution: def orderlyQueue(self, S: str, K: int) -> str: if K >= 2: return ''.join(sorted(list(S))) n = len(S) mc = min(list(S)) i = 0 j = 1 while j < n: if S[j] != mc: j += 1 continue k = 0 while k < n and S[(i+k)%n] == S[(j+k)%n]: k += 1 if S[(i+k)%n] > S[(j+k)%n]: i = j if k == 0: k = 1 j += k return S[i:] + S[:i] <file_sep>class Solution: def convertToBase7(self, num: int) -> str: if num == 0: return "0" res = [] negative = False if num < 0: negative = True num = -num while num > 0: res.append(str(num%7)) num //= 7 res.reverse() if negative: return "-" + "".join(res) return "".join(res) <file_sep>func isMatch(s string, p string) bool { m, n := len(s), len(p) dp := make([][]bool, m+1) for i := range dp { dp[i] = make([]bool, n+1) } dp[0][0] = true for j := 0; j < n; j++ { if p[j] == '*' { dp[0][j+1] = dp[0][j] } for i := 0; i < m; i++ { if s[i] == p[j] || p[j] == '?' { dp[i+1][j+1] = dp[i][j] } else if p[j] == '*' { dp[i+1][j+1] = dp[i+1][j] || dp[i][j+1] } } } return dp[m][n] }<file_sep>func reverseStr(s string, k int) string { n := len(s) s2 := make([]byte, n) for i := 0; i < n; i += 2 * k { z := i+k-1 if z > n - 1{ z = n -1 } for j := 0; j < k && i+j < n; j++ { s2[i+j] = s[z-j] } for j := 0; j < k && i+j+k < n; j++ { s2[i+j+k] = s[i+j+k] } } return string(s2) }<file_sep>class Solution: def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: edge = [[] for i in range(n+1)] for u, v, w in times: edge[u].append((v, w)) dp = [-1] * (n+1) dp[k] = 0 q = [(k, 0)] while len(q) > 0: u, t = q.pop() for v, w in edge[u]: if dp[v] == -1 or t + w < dp[v]: dp[v] = t + w q.append((v, dp[v])) if dp.count(-1) > 1: return -1 return max(dp[1:]) <file_sep>func canCross(stones []int) bool { n := len(stones) if stones[1] != 1 { return false } if n == 2 { return true } dp := make([][]bool, n) for i := range dp { dp[i] = make([]bool, n+1) } dp[1][1] = true for i := 2; i < n; i++ { for j := i - 1; j > 0; j-- { k := stones[i] - stones[j] if k > j+1 { break } dp[i][k] = dp[j][k-1] || dp[j][k] || dp[j][k+1] if i == n-1 && dp[i][k] { return true } } } return false }<file_sep>class Solution: def findMinDifference(self, timePoints: List[str]) -> int: timePoints = [int(t.split(":")[0])*60+int(t.split(":")[1]) for t in timePoints] timePoints.sort() print(timePoints) ret = min(timePoints[-1] - timePoints[0], timePoints[0] + 1440-timePoints[-1]) for i in range(1, len(timePoints)): ret = min(ret, timePoints[i] - timePoints[i-1]) ret = min(ret, timePoints[i-1] + 1440 - timePoints[i]) return ret<file_sep># Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def findBottomLeftValue(self, root): """ :type root: TreeNode :rtype: int """ self.h = 0 self.val = None self._find(root, 1) return self.val def _find(self, root, h): if root is None: return if h > self.h: self.h = h self.val = root.val self._find(root.left, h+1) self._find(root.right, h+1)<file_sep>class Solution(object): def removeSubfolders(self, folder): """ :type folder: List[str] :rtype: List[str] """ folder.sort() ret = [folder[0]] root = ret[0] for f in folder[1:]: if f.startswith(root) and f[len(root)] == '/': continue else: ret.append(f) root = f return ret<file_sep>class Solution: def rotate(self, nums: List[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. """ def gcd(a, b): if a % b == 0: return b else: return gcd(b, a%b) n = len(nums) k = k % n if k == 0: return g = gcd(n, k) l = n * k / g / k j = 0 x = nums[0] for i in range(n): #print(x, nums) jk = (j + k)%n y = nums[jk] nums[jk] = x x = y if g != 1 and (i+1) % l == 0: j = (j + k + 1) % n x = nums[j] else: j = jk<file_sep>import heapq as hq class Heap: def __init__(self, reverse=False): self._data = [] self._reverse = reverse def push(self, x): if self._reverse: hq.heappush(self._data, -x) else: hq.heappush(self._data, x) def pop(self): if self._reverse: return -hq.heappop(self._data) else: return hq.heappop(self._data) def front(self): if self._reverse: return -self._data[0] else: return self._data[0] def size(self): return len(self._data) class MedianFinder: def __init__(self): """ initialize your data structure here. """ self._minq = Heap() self._maxq = Heap(reverse=True) def addNum(self, num: int) -> None: if self._maxq.size() == 0 or num <= self._maxq.front(): self._maxq.push(num) else: self._minq.push(num) if self._maxq.size() - self._minq.size() > 1: self._minq.push(self._maxq.pop()) elif self._minq.size() - self._maxq.size() >= 1: self._maxq.push(self._minq.pop()) def findMedian(self) -> float: if (self._maxq.size() + self._minq.size()) % 2 == 1: return self._maxq.front() else: return (self._maxq.front() + self._minq.front()) / 2.0 # Your MedianFinder object will be instantiated and called as such: # obj = MedianFinder() # obj.addNum(num) # param_2 = obj.findMedian()<file_sep>class Solution: def findSubsequences(self, nums: List[int]) -> List[List[int]]: seqs = set() n = len(nums) def find(i, seq): if i == n: return find(i+1, seq) if len(seq) == 0 or seq[-1] <= nums[i]: seq.append(nums[i]) if len(seq) > 1: seqs.add(tuple(seq)) find(i+1, seq) seq.pop() find(0, []) return list(seqs)<file_sep>class Solution: def lengthOfLIS(self, nums: List[int]) -> int: seq = [nums[0]] def lower_bound(l, r, x): while l < r: m = (l + r) >> 1 if seq[m] < x: l = m + 1 else: r = m return r for num in nums: i = lower_bound(0, len(seq), num) if i == len(seq): seq.append(num) else: seq[i] = min(seq[i], num) return len(seq)<file_sep>class Solution: def partitionLabels(self, s: str) -> List[int]: count = {} for c in s: count[c] = count.get(c, 0) + 1 ret = [] p, size, x = set(), 0, 0 for c in s: size += 1 if c not in p: p.add(c) x += count[c] x -= 1 if x == 0: ret.append(size) p, size, x = set(), 0, 0 return ret <file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]: l1, l2 = None, None r1, r2 = None, None v1, v2 = 0, 0 if root1: v1 = root1.val l1, r1 = root1.left, root1.right if root2: v2 = root2.val l2, r2 = root2.left, root2.right if (not root1) and (not root2): return None node = TreeNode(v1+v2) node.left = self.mergeTrees(l1, l2) node.right = self.mergeTrees(r1, r2) return node<file_sep>type NumMatrix struct { row int col int sum [][]int } func Constructor(matrix [][]int) NumMatrix { numMatrix := NumMatrix{ row: len(matrix), col: len(matrix[0]), } numMatrix.sum = make([][]int, numMatrix.row+1) for i := 0; i < numMatrix.row+1; i++ { numMatrix.sum[i] = make([]int, numMatrix.col+1) } for i := 1; i <= numMatrix.row; i++ { for j := 1; j <= numMatrix.col; j++ { numMatrix.sum[i][j] = numMatrix.sum[i-1][j] + numMatrix.sum[i][j-1] - numMatrix.sum[i-1][j-1] + matrix[i-1][j-1] } } return numMatrix } func (this *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int) int { return this.sum[row2+1][col2+1] - this.sum[row1][col2+1] - this.sum[row2+1][col1] + this.sum[row1][col1] } <file_sep>class Solution: def scoreOfParentheses(self, s: str) -> int: ret = [] for c in s: if c == '(': ret.append(c) else: v = 0 while ret[-1] != '(': v += ret.pop() ret.pop() if v == 0: ret.append(1) else: ret.append(v*2) return sum(ret)<file_sep># Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def findTarget(self, root, k): """ :type root: TreeNode :type k: int :rtype: bool """ def treehas(node, val): while node: if node.val == val: return True elif val < node.val: node = node.left else: node = node.right return False def find(node, val): if node: return (val != node.val*2 and treehas(root, val-node.val)) or find(node.left, val) or find(node.right, val) return False return find(root, k) <file_sep>class Codec: def __init__(self): self._count = 0 self._l2surls = {} self._s2lurls = {} def encode(self, longUrl: str) -> str: """Encodes a URL to a shortened URL. """ if longUrl not in self._l2surls: self._count += 1 surl = f'https://tinyurl.com/${self._count}' self._s2lurls[surl] = longUrl self._l2surls[longUrl] = surl return self._l2surls[longUrl] def decode(self, shortUrl: str) -> str: """Decodes a shortened URL to its original URL. """ return self._s2lurls[shortUrl] # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.decode(codec.encode(url))<file_sep>class Solution: def minPathSum(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) inf = float('inf') sum = [[inf for j in range(n)] for i in range(m)] sum[0][0] = grid[0][0] for i in range(m): for j in range(n): if i-1>=0: sum[i][j] = min(sum[i][j], sum[i-1][j] + grid[i][j]) if j-1>=0: sum[i][j] = min(sum[i][j], sum[i][j-1] + grid[i][j]) return sum[-1][-1]<file_sep>class Solution: def judgeSquareSum(self, c: int) -> bool: from math import sqrt squares = set([i*i for i in range(int(sqrt(c))+1)]) for square in squares: if c - square in squares: return True return False<file_sep>class Solution: def letterCasePermutation(self, s: str) -> List[str]: ret = [s] s = list(s) n = len(s) def get_permutation(i): if i == n: return c = s[i] if 'a' <= s[i] <= 'z': s[i] = chr(ord(s[i]) - 32) ret.append(''.join(s)) get_permutation(i+1) elif 'A' <= s[i] <= 'Z': s[i] = chr(ord(s[i]) + 32) ret.append(''.join(s)) get_permutation(i+1) s[i] = c get_permutation(i+1) get_permutation(0) return ret <file_sep>class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: n = numCourses d = [0] * n edge = [[] for i in range(n)] for a, b in prerequisites: d[a] += 1 edge[b].append(a) course = 0 tp = [] for i in range(n): if d[i] == 0: tp.append(i) while len(tp) > 0: course += 1 x = tp.pop() for e in edge[x]: d[e] -= 1 if d[e] == 0: tp.append(e) return course == n <file_sep># @param {Integer} n # @return {Integer} def integer_break(n) dp = Array.new(n+1, 1) for i in 3..n for j in 1..i-1 x = [j, dp[j]].max y = [i-j, dp[i-j]].max z = x * y dp[i] = z if z > dp[i] end end dp[n] end <file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]: def toBST(l, r): if l >= r: return None m = (l + r) // 2 node = TreeNode(nums[m]) node.left = toBST(l, m) node.right = toBST(m+1, r) return node return toBST(0, len(nums))<file_sep>class Solution: def numberOfSubarrays(self, nums: List[int], k: int) -> int: n = len(nums) ret = 0 x = 0 odd = {0:1} for num in nums: if num % 2 == 1: x += 1 odd[x] = odd.get(x, 0) + 1 for x in odd: y = odd.get(x-k, 0) ret += odd[x] * y return ret <file_sep>import threading class ZeroEvenOdd: def __init__(self, n): self.n = n self.lock0 = threading.Lock() self.lock1 = threading.Lock() self.lock2 = threading.Lock() self.lock1.acquire() self.lock2.acquire() # printNumber(x) outputs "x", where x is an integer. def zero(self, printNumber: 'Callable[[int], None]') -> None: for i in range(self.n): self.lock0.acquire() printNumber(0) if i % 2 == 0: self.lock1.release() else: self.lock2.release() def even(self, printNumber: 'Callable[[int], None]') -> None: for i in range(2, self.n+1, 2): self.lock2.acquire() printNumber(i) self.lock0.release() def odd(self, printNumber: 'Callable[[int], None]') -> None: for i in range(1, self.n+1, 2): self.lock1.acquire() printNumber(i) self.lock0.release() <file_sep>class Solution: def maximumSwap(self, num: int) -> int: digits = [int(i) for i in list(str(num))] sorted_digits = sorted(digits, reverse=True) n = len(digits) for i in range(n): if digits[i] == sorted_digits[i]: continue for j in range(n-1, i, -1): if digits[j] == sorted_digits[i]: digits[i], digits[j] = digits[j], digits[i] break break return int(''.join([str(i) for i in digits]))<file_sep># Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None ''' Notes: If the two linked lists have no intersection at all, return null. The linked lists must retain their original structure after the function returns. You may assume there are no cycles anywhere in the entire linked structure. Your code should preferably run in O(n) time and use only O(1) memory. ''' class Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ a, b = headA, headB while a or b: if a == b: return a if a: a = a.next else: a = headB if b: b = b.next else: b = headA return None <file_sep>class Solution: def splitIntoFibonacci(self, S: str) -> List[int]: n = len(S) inf = (1<<31) - 1 for i in range(1, n): for j in range(i+1, n): k = 0 ret = [] while 1: a, b = S[k:i], S[i:j] if (a.startswith('0') and len(a) > 1) or (b.startswith('0') and len(b) > 1) or len(a) == 0 or len(b) == 0: break x, y = int(a), int(b) z = x+y c = str(z) if not S[j:].startswith(c): break if x >inf or y >inf or z >inf : break if k == 0: ret = [x, y] ret.append(z) k, i, j = i, j, j+len(c) if j == n: return ret return []<file_sep>class Solution: def maxRotateFunction(self, nums: List[int]) -> int: n = len(nums) sumNums = sum(nums) ret = sum([i * nums[i] for i in range(n)]) f = ret for i in range(0, n-1): f = f - sumNums + n * nums[i] ret = max(ret, f) return ret<file_sep># @param {Integer[]} nums # @return {Integer} def find_unsorted_subarray(nums) nums2 = nums.sort n = nums.length i, j = 0, n-1 while i < n && nums[i] == nums2[i] then i+=1 end while j > i && nums[j] == nums2[j] then j-=1 end j-i+1 end<file_sep># Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def swapPairs(self, head: ListNode) -> ListNode: if (not head) or (not head.next): return head ret = head.next left, right = None, head while right: n1, n2 = right, right.next if n2: if left: left.next = n2 left = n1 right = n2.next n1.next = None n2.next = n1 else: left.next = n1 break return ret <file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: res = [] q = [root] while len(q) > 0: val = 0 q2 = [] for node in q: val += node.val if node.left: q2.append(node.left) if node.right: q2.append(node.right) res.append(val/len(q)) q = q2 return res <file_sep>class Solution(object): def xorQueries(self, arr, queries): """ :type arr: List[int] :type queries: List[List[int]] :rtype: List[int] """ n = len(arr) for i in range(1, n): arr[i] = arr[i] ^ arr[i-1] ret = [] for x, y in queries: if x == 0: ret.append(arr[y]) else: ret.append(arr[x-1]^arr[y]) return ret<file_sep>bool canPartition(int* nums, int numsSize) { if (numsSize <=0) return false; int max = numsSize * 100; bool *dp = malloc(max * sizeof(bool)); memset(dp, 0, max * sizeof(bool)); dp[0] = true; bool ret = false; int sum = 0; for(int i=0;i<numsSize; ++i) { sum += nums[i]; for(int j=max-1; j>=nums[i]; --j) { dp[j] |= dp[j-nums[i]]; } } if (!(sum&1)) { ret = dp[sum>>1]; } free(dp); return ret; }<file_sep>class Solution(object): def constructRectangle(self, area): """ :type area: int :rtype: List[int] """ import math sq = int(math.sqrt(area)) for i in range(sq, 0, -1): if area % i == 0: return sorted([i, area/i], reverse=True) return [area, 1] <file_sep>class Solution { public: int evalRPN(vector<string>& tokens) { stack<long>st; long l, r; for (auto t : tokens) { char firstchar = '0'; if (t.length() == 1) { firstchar = t[0]; } switch (firstchar) { case '+': r = st.top(); st.pop(); l = st.top(); st.pop(); st.push(l + r); break; case '-': r = st.top(); st.pop(); l = st.top(); st.pop(); st.push(l - r); break; case '*': r = st.top(); st.pop(); l = st.top(); st.pop(); st.push(l*r); break; case '/': r = st.top(); st.pop(); l = st.top(); st.pop(); st.push(l / r); break; default: l = stol(t); st.push(l); break; } } return st.top(); } };<file_sep>class Solution(object): def exist(self, board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """ m = len(board) n = len(board[0]) vis = [[False for j in range(n)] for i in range(m)] def dfs(i, j, k): if i <0 or i >=m or j<0 or j>=n or vis[i][j] or board[i][j]!=word[k]: return False k+=1 if k == len(word): return True vis[i][j] = True if dfs(i-1, j, k) or dfs(i+1, j, k) or dfs(i, j-1, k) or dfs(i, j+1, k): return True vis[i][j] = False return False for i in range(m): for j in range(n): if dfs(i, j, 0): return True return False <file_sep>func maxNumber(nums1 []int, nums2 []int, k int) []int { maxN := func(nums []int, k int) []int { stack := make([]int, 0) for i, num := range nums { for len(stack) > 0 && stack[len(stack)-1] < num && len(stack)+len(nums)-i > k { stack = stack[:len(stack)-1] } if len(stack) < k { stack = append(stack, num) } } return stack } merge := func(nums1, nums2 []int) []int { nums := make([]int, 0) i, j := 0, 0 for i < len(nums1) || j < len(nums2) { if i == len(nums1) { nums = append(nums, nums2[j:]...) break } if j == len(nums2) { nums = append(nums, nums1[i:]...) break } if nums1[i] < nums2[j] { nums = append(nums, nums2[j]) j++ } else if nums1[i] > nums2[j] { nums = append(nums, nums1[i]) i++ } else { k := 0 for i+k < len(nums1) && j+k < len(nums2) && nums1[i+k] == nums2[j+k] { k++ } if i+k == len(nums1) { nums = append(nums, nums2[j]) j++ } else if j+k == len(nums2) { nums = append(nums, nums1[i]) i++ } else if nums1[i+k] < nums2[j+k] { nums = append(nums, nums2[j]) j++ } else { nums = append(nums, nums1[i]) i++ } } } return nums } max := func(nums1, nums2 []int) []int { for i := 0; i < len(nums1); i++ { if nums1[i] < nums2[i] { return nums2 } else if nums1[i] > nums2[i] { return nums1 } } return nums1 } res := make([]int, k) for i := 0; i <= k; i++ { if i <= len(nums1) && k-i <= len(nums2) { res = max(res, merge(maxN(nums1, i), maxN(nums2, k-i))) } } return res }<file_sep>func kSmallestPairs(nums1 []int, nums2 []int, k int) [][]int { n1, n2 := len(nums1), len(nums2) res := make([][]int, 0, k) first := make([][2]int, 0, n1) first = append(first, [2]int{0, 0}) for len(res) < k && len(first) > 0 { min := math.MaxInt32 for j := 0; j < len(first); j++ { sum := nums1[first[j][0]] + nums2[first[j][1]] if sum < min { min = sum } } if first[len(first)-1][0]+1 < n1 && nums1[first[len(first)-1][0]+1]+nums2[0] <= min { first = append(first, [2]int{first[len(first)-1][0] + 1, 0}) min = nums1[first[len(first)-1][0]] + nums2[0] } offset := 0 for j := 0; j < len(first) && len(res) < k; j++ { sum := nums1[first[j][0]] + nums2[first[j][1]] if sum == min { res = append(res, []int{nums1[first[j][0]], nums2[first[j][1]]}) first[j][1]++ if first[j][1] == n2 { offset++ if offset == len(first) && first[len(first)-1][0]+1 < n1 { first = append(first, [2]int{first[len(first)-1][0] + 1, 0}) } } } } first = first[offset:] } return res }<file_sep>class Solution(object): def validUtf8(self, data): """ :type data: List[int] :rtype: bool """ i = 0 n = len(data) while i < n: if data[i] & 0xf8 == 0xf0: j = 3 elif data[i] & 0xf0 == 0xe0: j = 2 elif data[i] & 0xe0 == 0xc0: j = 1 elif data[i] & 0x80 == 0: j = 0 else: return False print 'i, j = ', i, j for k in xrange(j): i += 1 if i >= n: return False if data[i] & 0xc0 != 0x80: return False i += 1 print 'i = ', i return i == n <file_sep>class Solution: def evalRPN(self, tokens: List[str]) -> int: q = [] for tok in tokens: #print(q) if tok == '+': q.append(q.pop() + q.pop()) elif tok == '-': b, a = q.pop(), q.pop() q.append(a - b) elif tok == '*': q.append(q.pop() * q.pop()) elif tok == '/': b, a = q.pop(), q.pop() q.append(int(a/b)) else: q.append(int(tok)) return q[0]<file_sep>class Solution: def mincostTickets(self, days: List[int], costs: List[int]) -> int: n = len(days) dp = [float('inf')] * (n + 1) dp[-1] = 0 for i in range(n): #costs[0] dp[i] = min(dp[i], dp[i-1] + costs[0]) #costs[1] j = i while j < n and days[j] - days[i] < 7: dp[j] = min(dp[j], dp[i-1] + costs[1]) j += 1 #cost[2] j = i while j < n and days[j] - days[i] < 30: dp[j] = min(dp[j], dp[i-1] + costs[2]) j += 1 #print(dp) return dp[n-1] <file_sep>class Solution(object): def countAndSay(self, n): """ :type n: int :rtype: str """ if n<1: return '' ret = '1' for i in range(n-1): x = [] n = len(ret) i = 0 while i < n: j = i+1 while j < n and ret[i] == ret[j]: j += 1 x.append(str(j-i)) x.append(ret[i]) i = j ret = ''.join(x) return ret <file_sep>class Solution: def getSquares(self, n): ret = [] for i in range(1, n): if i*i <= n: ret.append(i*i) else: break return ret def numSquares(self, n: int) -> int: squares = self.getSquares(n) dp = [n] * (n+1) dp[0] = 0 for i in range(1, n+1): for s in squares: if i-s >= 0: dp[i] = min(dp[i], dp[i-s]+1) else: break #print(dp) return dp[n]<file_sep>func maxArea(height []int) int { res := 0 l, r := 0, len(height)-1 lmax, rmax := height[l], height[r] max := func(a, b int) int { if a < b { return b } return a } for l < r { lmax = max(lmax, height[l]) rmax = max(rmax, height[r]) if lmax < rmax { res = max(res, lmax*(r-l)) l++ } else { res = max(res, rmax*(r-l)) r-- } } return res }<file_sep># @param {Integer[][]} matrix # @return {Integer[]} def find_diagonal_order(matrix) if matrix == nil or matrix.length == 0 then return [] end ret = [] m = matrix.length n = matrix[0].length i, j, up = 0, 0, false while true up = !up if up while i >= 0 and j < n ret << matrix[i][j] i -= 1; j += 1 end i += 1; j -= 1 if j < n - 1 j += 1 elsif i < m - 1 i += 1 else break end else while i < m and j >= 0 ret << matrix[i][j] i += 1; j -= 1 end i -= 1; j += 1; if i < m - 1 i += 1 elsif j < n - 1 j += 1 else break end end end return ret end<file_sep>func validUtf8(data []int) bool { n := len(data) i := 0 for i < n { // 4 bytes if data[i]&0xf8 == 0xf0 { if i+4 > n || data[i+1]&0xc0 != 0x80 || data[i+2]&0xc0 != 0x80 || data[i+3]&0xc0 != 0x80 { return false } i += 4 } else if data[i]&0xf0 == 0xe0 { if i+3 > n || data[i+1]&0xc0 != 0x80 || data[i+2]&0xc0 != 0x80 { return false } i += 3 } else if data[i]&0xe0 == 0xc0 { if i+2 > n || data[i+1]&0xc0 != 0x80 { return false } i += 2 } else if data[i]&0x80 == 0 { i++ } else { return false } } return true } <file_sep># Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ def to_list(arr, node): if not node: arr.append('None') return arr.append(str(node.val)) to_list(arr, node.left) to_list(arr, node.right) arr = [] to_list(arr, root) return ','.join(arr) def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ def from_list(arr): item = arr.pop() if item == 'None': return None node = TreeNode(int(item)) node.left = from_list(arr) node.right = from_list(arr) return node arr = list(data.split(',')) arr.reverse() return from_list(arr) # Your Codec object will be instantiated and called as such: # ser = Codec() # deser = Codec() # ans = deser.deserialize(ser.serialize(root))<file_sep>class Solution(object): def nthSuperUglyNumber(self, n, primes): """ :type n: int :type primes: List[int] :rtype: int """ m = len(primes) f = [0] * m ret = [1] while len(ret) < n: mi = float('inf') for i in range(m): num = ret[f[i]]*primes[i] while num <= ret[-1]: f[i] += 1 num = ret[f[i]]*primes[i] mi = min(mi, num) ret.append(mi) return ret[n-1] <file_sep># @param {Integer[]} nums # @return {Integer[][]} def three_sum(nums) ret = [] nums.sort! for i in 0..nums.length-1 if i > 0 and nums[i] == nums[i-1] then next end l, r = i+1, nums.length-1 while l < r sum = nums[i] + nums[l] + nums[r] if sum < 0 then l += 1 elsif sum > 0 then r -= 1 else ret << [nums[i], nums[l], nums[r]] while l < r and nums[l] == nums[l + 1] do l += 1 end while l < r and nums[r] == nums[r - 1] do r -= 1 end l += 1 r -= 1 end end end return ret end <file_sep>class Solution: def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]: m, n = len(mat), len(mat[0]) visited = [[False] * n for _ in range(m)] res = [[0] * n for _ in range(m)] moves = ((1, 0), (-1, 0), (0, 1), (0, -1)) q = [] for i in range(m): for j in range(n): if mat[i][j] == 1: res[i][j] = -1 else: visited[i][j] = True q.append((i,j)) k = 0 while len(q) > 0: q2 = [] for x, y in q: if mat[x][y] == 1: res[x][y] = k for dx, dy in moves: x2, y2 = x+dx, y+dy if x2<0 or x2>=m or y2<0 or y2>=n or visited[x2][y2]: continue visited[x2][y2] = True q2.append((x2, y2)) k += 1 q = q2 return res <file_sep>class Solution: def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]: from functools import cmp_to_key def cmp(a, b): if a[0] != b[0]: return a[0] - b[0] return a[1] - b[1] people.sort(key=cmp_to_key(cmp)) people.reverse() n = len(people) ret = [0] * n while len(people) > 0: p = people.pop() h, k = p k += 1 for i in range(n): if ret[i] == 0 or ret[i][0] >= h: k -= 1 if k == 0: break ret[i] = p return ret<file_sep>class Solution(object): def canMeasureWater(self, x, y, z): """ :type x: int :type y: int :type z: int :rtype: bool """ if x == 0 or y == 0: return x == z or y == z def gcd(a, b): if b == 0: return a return gcd(b, a%b) g = gcd(x, y) return z <= x + y and z % g == 0 <file_sep>class Solution: def sortArrayByParityII(self, A: List[int]) -> List[int]: odd = list(filter(lambda x: x%2 != 0, A)) even = list(filter(lambda x: x%2 == 0, A)) n = len(A) ret = [] for i in range(n//2): ret.append(even.pop()) ret.append(odd.pop()) return ret <file_sep>func eraseOverlapIntervals(intervals [][]int) int { n := len(intervals) if n <= 1 { return 0 } less := func(i, j int) bool { if intervals[i][0] == intervals[j][0] { return intervals[i][1] < intervals[j][1] } return intervals[i][0] < intervals[j][0] } sort.Slice(intervals, less) res := 0 right := intervals[0][1] for i := 1; i < n; i++ { if intervals[i][0] < right { res++ if intervals[i][1] < right { right = intervals[i][1] } } else { right = intervals[i][1] } } return res }<file_sep># @param {Integer[]} nums # @return {String[]} def summary_ranges(nums) def range2str(start, finish) return start == finish ? (start.to_s) : ("#{start}->#{finish}") end ret = [] start = nil finish = nil for i in nums if start == nil start = i finish = i elsif finish + 1 == i finish = i else ret << range2str(start, finish) start = i finish = i end end if start != nil ret << range2str(start, finish) end return ret end <file_sep># Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: if len(lists) == 0: return None def merge(a, b): head = ListNode(0) node = head while a and b: if a.val <= b.val: node.next = a a = a.next else: node.next = b b = b.next node = node.next if a: node.next = a if b: node.next = b return head.next while len(lists) > 1: lists2 = [] while len(lists) > 1: a, b = lists.pop(), lists.pop() lists2.append(merge(a, b)) if len(lists) > 0: lists2.append(lists[0]) lists = lists2 return lists[0]<file_sep># Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def maxPathSum(self, root): """ :type root: TreeNode :rtype: int """ ninf = -float('inf') ret = [ninf] def path(root): if not root: return ninf l= path(root.left) r = path(root.right) y = root.val if l>0: y+=l if r>0: y+=r ret[0]=max(ret[0], y) return max(root.val, max(root.val+l, root.val+r)) path(root) return ret[0] <file_sep># Definition for a binary tree node. # class TreeNode # attr_accessor :val, :left, :right # def initialize(val) # @val = val # @left, @right = nil, nil # end # end # @param {TreeNode} s # @param {TreeNode} t # @return {Boolean} def is_subtree(s, t) def is_sub(s, t) if s==nil and t==nil then return true end if s==nil or t == nil or s.val != t.val then return false end if !is_sub(s.left, t.left) then return false end if !is_sub(s.right, t.right) then return false end return true end if is_sub(s, t) then return true end if s.left and is_subtree(s.left, t) then return true end if s.right and is_subtree(s.right, t) then return true end return false end<file_sep>func getPermutation(n int, k int) string { fn := 1 for i := 1; i <= n; i++ { fn *= i } used := make([]bool, n+1) res := make([]byte, 0, n) for i := 0; i < n; i++ { fn /= n - i count := 0 for j := 1; j <= n; j++ { if used[j] { continue } count += fn if count >= k { res = append(res, byte(j)+'0') used[j] = true k -= count - fn break } } } return string(res) }<file_sep>class Solution(object): def canCross(self, stones): """ :type stones: List[int] :rtype: bool """ n = len(stones) if stones[1] != 1: return False dp = {} for i in stones: dp[i] = [] dp[1].append(1) for i in stones: for st in dp[i]: for k in [-1, 0, 1]: x = i + st + k if x in dp: y = st + k if y not in dp[x]: dp[x].append(y) return len(dp[stones[-1]]) > 0 <file_sep>class Solution(object): def combinationSum(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ self.ret = [] self.arr = candidates self._dfs(len(candidates)-1, target, []) return self.ret def _dfs(self, i, sum, l): if sum == 0: self.ret.append(l[:]) return if i < 0 or sum < 0: return self._dfs(i-1, sum, l) for k in range(sum/self.arr[i]): l.append(self.arr[i]) self._dfs(i-1, sum-(k+1)*self.arr[i], l) for k in range(sum/self.arr[i]): l.pop()<file_sep>class Solution(object): def findLUSlength(self, a, b): """ :type a: str :type b: str :rtype: int """ l1, l2 = len(a), len(b) if l1 != l2: return max(l1, l2) if a != b: return l1 return -1 <file_sep>func wordPattern(pattern string, s string) bool { words := strings.Split(s, " ") if len(words) != len(pattern) { return false } m := make(map[byte]string) m2 := make(map[string]bool) for i := 0; i < len(pattern); i++ { if m[pattern[i]] == "" && !m2[words[i]] { m[pattern[i]] = words[i] m2[words[i]] = true } else if m[pattern[i]] != words[i] { return false } } return true }<file_sep>func reverse(x int) int { isOverflowMul := func(x, y int32) bool { if x == 0 || y == 0 { return false } if x*y/x != y || x*y/y != x { return true } return false } isOverflowAdd := func(x, y int32) bool { if x == 0 || y == 0 || (x < 0) != (y < 0) { return false } if x > 0 && (x+y < x || x+y < y) { return true } if x < 0 && (x+y > x || x+y > y) { return true } return false } isOverflowMul(0, 0) isOverflowAdd(0, 0) var res int32 = 0 y := 0 for x != 0 { x, y = x/10, x%10 if isOverflowMul(res, 10) || isOverflowAdd(res*10, int32(y)) { return 0 } res = res*10 + int32(y) } return int(res) }<file_sep>func validSquare(p1 []int, p2 []int, p3 []int, p4 []int) bool { pow2 := func(x int) int { return x * x } valid := func(x, y, z []int) bool { a := pow2(x[0]-y[0]) + pow2(x[1]-y[1]) b := pow2(x[0]-z[0]) + pow2(x[1]-z[1]) c := pow2(y[0]-z[0]) + pow2(y[1]-z[1]) return (a == b && a+b == c && c > 0) || (a == c && a+c == b && b > 0) || (b == c && b+c == a && a > 0) } return valid(p1, p2, p3) && valid(p1, p2, p4) && valid(p1, p3, p4) && valid(p2, p3, p4) } <file_sep>class Solution: def is_close(self, grid, n, m, x, y): ret = 1 q = [(x, y)] while len(q) > 0: a, b = q.pop() if a < 0 or a >= n or b < 0 or b >= m or grid[a][b] != 0: continue if a == 0 or a == n-1 or b == 0 or b == m - 1: ret = 0 grid[a][b] = 1 q.append((a+1, b)) q.append((a-1, b)) q.append((a, b+1)) q.append((a, b-1)) return ret def closedIsland(self, grid: List[List[int]]) -> int: ret = 0 n, m = len(grid), len(grid[0]) for i in range(n): for j in range(m): if grid[i][j] == 0: ret += self.is_close(grid, n, m, i, j) return ret<file_sep>class Solution: def nthUglyNumber(self, n: int) -> int: dp = [1] * (n+1) p2, p3, p5 = 1, 1, 1 for i in range(2, n+1): num2, num3, num5 = dp[p2] * 2, dp[p3] * 3, dp[p5] * 5 dp[i] = min(num2, num3, num5) if dp[i] == num2: p2 += 1 if dp[i] == num3: p3 += 1 if dp[i] == num5: p5 += 1 return dp[n]<file_sep>func rotate(matrix [][]int) { m := matrix n := len(m) for i := 0; i < n/2; i++ { for j := 0; j < n-i*2-1; j++ { a := &m[i][i+j] b := &m[i+j][n-i-1] c := &m[n-i-1][n-i-j-1] d := &m[n-i-j-1][i] *a, *b, *c, *d = *d, *a, *b, *c } } }<file_sep> func checkSubarraySum(nums []int, k int) bool { n := len(nums) if n < 2 { return false } sum := 0 mp := make(map[int]int) for i := 0; i < n; i++ { nums[i] = nums[i] % k if i > 0 && nums[i] == 0 && nums[i-1] == 0 { return true } if nums[i] == 0 { continue } sum = (sum + nums[i]) % k if sum == 0 && i > 0 { return true } if _, ok := mp[sum]; ok { return true } mp[sum] = i } return false } <file_sep>class Solution(object): def findLengthOfLCIS(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 ret=0 n = len(nums) k=1 for i in range(1, n): if nums[i]>nums[i-1]: k +=1 ret = max(ret, k) else: k = 1 ret = max(ret, k) return ret <file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: def prune(node): if not node: return 0 l, r = prune(node.left), prune(node.right) if l == 0: node.left = None if r == 0: node.right = None return node.val | l | r if (not root) or ((root.val | prune(root)) == 0): return None return root <file_sep># Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def minDepth(self, root): """ :type root: TreeNode :rtype: int """ self.h = float('inf') self._min(root, 1) return self.h if self.h != float('inf') else 0 def _min(self, root, h): if root is None: return if root.left is None and root.right is None: self.h = min(self.h, h) self._min(root.left, h+1) self._min(root.right, h+1)<file_sep>class Solution(object): def checkSubarraySum(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ for i in range(1, len(nums)): if nums[i-1] == 0 and nums[i] == 0: return True if k == 0: return False k=abs(k) sumSet = set() s = 0 pre = 0 for i in nums: s += i s %= k if s in sumSet: return True sumSet.add(pre) pre = s return False <file_sep>func isScramble(s1 string, s2 string) bool { m, n := len(s1), len(s2) if m != n { return false } dp := make([][][]bool, n) for i := 0; i < n; i++ { dp[i] = make([][]bool, n) for j := 0; j < n; j++ { dp[i][j] = make([]bool, n+1) if s1[i] == s2[j] { dp[i][j][1] = true } } } for k := 2; k <= n; k++ { for i := 0; i+k <= n; i++ { for j := 0; j+k <= n; j++ { for x := 1; x < k; x++ { if dp[i][j][x] && dp[i+x][j+x][k-x] { dp[i][j][k] = true break } if dp[i][j+k-x][x] && dp[i+x][j][k-x] { dp[i][j][k] = true break } } } } } return dp[0][0][n] } <file_sep>class Solution(object): def subarraySum(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ def binSearch(arr, target): l, r = 0, len(arr) while l < r: m = (l+r)/2 if arr[m] < target: l = m + 1 else: r = m return l ret = 0 s = 0 n = len(nums) index = {0: [0]} sums = [0] * n for i in range(n): s += nums[i] sums[i] = s if s in index: index[s].append(i+1) else: index[s] = [i+1] for i in range(n): x = sums[i] - k ret += binSearch(index.get(x, []), i+1) return ret <file_sep>class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: sets = [[]] for num in nums: sets = sets + [s+[num] for s in sets] return sets<file_sep>class NumArray: def __init__(self, nums: List[int]): n = len(nums) self._sum = [0] * (n+1) self._sum[0] = nums[0] for i in range(1, n): self._sum[i] = self._sum[i-1] + nums[i] def sumRange(self, left: int, right: int) -> int: return self._sum[right] - self._sum[left-1] # Your NumArray object will be instantiated and called as such: # obj = NumArray(nums) # param_1 = obj.sumRange(left,right) <file_sep>class Solution: def generateParenthesis(self, n: int) -> List[str]: ans = [] def generate(left, right, s): if left == 0 and right == 0: ans.append(s) return if left > 0: generate(left-1, right, s+"(") if right > left: generate(left, right-1, s+")") generate(n, n, "") return ans<file_sep>class Solution: def maxSubArray(self, nums: List[int]) -> int: maxSum = nums[0] currentSum = nums[0] for i in nums[1:]: currentSum = max(currentSum+i, i) maxSum = max(maxSum, currentSum) return maxSum<file_sep># Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def partition(self, head, x): """ :type head: ListNode :type x: int :rtype: ListNode """ s1 = [ListNode(0)] s2 = [ListNode(0)] while head: if head.val < x: s1.append(head) else: s2.append(head) head = head.next for i in range(len(s1)-1): s1[i].next = s1[i+1] for i in range(len(s2)-1): s2[i].next = s2[i+1] s2[-1].next = None s1[-1].next = s2[0].next return s1[0].next <file_sep>class Solution: def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]: m, n = len(mat), len(mat[0]) if m * n != r * c: return mat res = [[0]*c for _ in range(r)] for i in range(r): for j in range(c): k = i*c + j res[i][j] = mat[k//n][k%n] return res <file_sep># Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ l = [] def _tostr(node): if node is None: l.append('null') else: l.append(str(node.val)) _tostr(node.left) _tostr(node.right) _tostr(root) return ','.join(l) def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ l = data.split(',') pos = [0] def _totree(): i = pos[0] pos[0] += 1 if i >=len(l) or l[i] == 'null': return None node = TreeNode(int(l[i])) node.left = _totree() node.right = _totree() return node return _totree() # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.deserialize(codec.serialize(root))<file_sep>class Solution(object): def plusOne(self, digits): """ :type digits: List[int] :rtype: List[int] """ digits = digits[::-1] s = 1 for i in range(len(digits)): s = s + digits[i] digits[i] = s%10 s /= 10 if s > 0: digits.append(s) return digits[::-1] <file_sep>class Solution: def addBinary(self, a: str, b: str) -> str: a, b = list(a), list(b) a.reverse() b.reverse() c = [0] i = 0 x = 0 while i < len(a) or i < len(b) or x > 0: if i >= len(c): c.append(0) c[i] += x if i < len(a): c[i] += int(a[i]) if i < len(b): c[i] += int(b[i]) if c[i] > 1: x = c[i] // 2 c[i] = c[i] % 2 else: x = 0 i += 1 c.reverse() return ''.join(map(lambda x: str(x), c))<file_sep>class Solution: def numberOfArithmeticSlices(self, nums: List[int]) -> int: from collections import defaultdict n = len(nums) dp = [defaultdict(int) for _ in range(n)] res = 0 for i in range(n): for j in range(i): diff = nums[i] - nums[j] x = dp[j][diff] dp[i][diff] += x + 1 res += x return res<file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def findTilt(self, root: Optional[TreeNode]) -> int: def find(node): if not node: return 0, 0 ls, lt = find(node.left) rs, rt = find(node.right) return node.val + ls + rs, abs(ls-rs) + lt + rt s, t = find(root) return t<file_sep>class Solution: def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: candidates.sort() n = len(candidates) q = [(0, 0, [])] ret = [] while len(q) > 0: i, s, nums = q.pop() #print(i, s, nums) if s == target: ret.append(nums) continue if i >= n or s + candidates[i] > target: continue k = i + 1 while k < n and candidates[i] == candidates[k]: k += 1 q.append((k, s, nums)) j = i + 1 while j <= k: if s + candidates[i] * (j-i) <= target: q.append((k, s + candidates[i] * (j-i), nums+[candidates[i]]*(j-i))) else: break j += 1 return ret <file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool: if not root: return False def issub(n1, n2): if n1 == None and n2 == None: return True if (n1 == None) != (n2 == None): return False if n1.val != n2.val: return False return issub(n1.left, n2.left) and issub(n1.right, n2.right) return issub(root, subRoot) or self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot) <file_sep>class Solution(object): def licenseKeyFormatting(self, S, K): """ :type S: str :type K: int :rtype: str """ S = S.replace('-', '') S = S.upper() n = len(S) ret = [] for i in range(n, 0, -K): ret.append(S[max(0, i-K):i]) ret.reverse() return '-'.join(ret)<file_sep># Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: h1, h2 = head, head while n != 0: n -= 1 h2 = h2.next if not h2: return head.next while h2.next: h1 = h1.next h2 = h2.next if h1.next: h1.next = h1.next.next else: h1.next = None return head <file_sep>class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: n = len(graph) ret = [] path = [0] * n def dfs(i, p, q): path[i] = p if p == q: ret.append(path[:i+1]) return for j in graph[p]: dfs(i+1, j, q) dfs(0, 0, n-1) return ret <file_sep>class Solution(object): def solveSudoku(self, board): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ row = [set() for i in range(9)] col = [set() for i in range(9)] grid = [[set() for j in range(3)] for i in range(3)] si = [str(i) for i in range(10)] for i in range(9): for j in range(9): if board[i][j] == '.': continue x = int(board[i][j]) row[i].add(x) col[j].add(x) grid[i/3][j/3].add(x) def solve(k): if k == 81: return True x, y = k/9, k%9 if board[x][y] != '.': return solve(k+1) for i in range(1, 10): if (i in row[x]) or (i in col[y]) or (i in grid[x/3][y/3]): continue row[x].add(i) col[y].add(i) grid[x/3][y/3].add(i) board[x][y] = si[i] if solve(k+1): return True row[x].remove(i) col[y].remove(i) grid[x/3][y/3].remove(i) board[x][y] = '.' return False solve(0) <file_sep># Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode: root = ListNode(0, head) i = 0 preNode = None node = root l1, l2 = None, None while node: if i == left: l1, l2 = preNode, node elif i == right: l1.next = node l2.next = node.next nextNode = node.next if left < i <= right: node.next = preNode preNode = node node = nextNode i += 1 return root.next <file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isValidBST(self, root: TreeNode) -> bool: dmax = {} dmin = {} def _max(node): if node in dmax: return dmax[node] ret = node.val if node.left: ret = max(ret, _max(node.left)) if node.right: ret = max(ret, _max(node.right)) dmax[node] = ret return ret def _min(node): if node in dmin: return dmin[node] ret = node.val if node.left: ret = min(ret, _min(node.left)) if node.right: ret = min(ret, _min(node.right)) dmin[node] = ret return ret def valid(node): if not node: return True if node.left and node.val <= _max(node.left): return False if node.right and node.val >= _min(node.right): return False return valid(node.left) and valid(node.right) return valid(root) <file_sep># Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: root = ListNode(0) h = root l1, l2 = list1, list2 while l1 and l2: if l1.val <= l2.val: h.next = l1 l1 = l1.next else: h.next = l2 l2 = l2.next h = h.next while l1: h.next = l1 l1 = l1.next h = h.next while l2: h.next = l2 l2 = l2.next h = h.next return root.next <file_sep>class Solution: def lexicalOrder(self, n: int) -> List[int]: ret = [] def getNums(num): ret.append(num) for i in range(10): num2 = num * 10 + i if num2 <= n: getNums(num2) else: break for i in range(1, min(10, n+1)): getNums(i) return ret<file_sep>class Solution: def pancakeSort(self, arr: List[int]) -> List[int]: def reverse(array, a, b): while a < b: array[a], array[b] = array[b], array[a] a += 1 b -= 1 ret = [] n = len(arr) i = n while i > 0: j = arr.index(i) if j+1 == i: i -= 1 continue ret.append(j+1) ret.append(i) reverse(arr, 0, j) reverse(arr, 0, i-1) return ret <file_sep>class Solution(object): def findSubsequences(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ ret = set() n = len(nums) def findall(i, l): if len(l) >=2: ret.add(tuple(l)) if i >=n: return findall(i+1, l) if len(l) == 0 or nums[i] >= l[-1]: l.append(nums[i]) findall(i+1, l) l.pop() findall(0, []) return list(ret) <file_sep>import math class Solution(object): def poorPigs(self, buckets, minutesToDie, minutesToTest): """ :type buckets: int :type minutesToDie: int :type minutesToTest: int :rtype: int """ if buckets <= 1: return 0 if minutesToDie < 1: return 1 n = buckets k = (minutesToTest / minutesToDie) + 1 print k ret = int(math.log(n)/math.log(k)) if k ** ret < n: ret += 1 return ret <file_sep>class Solution: def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: p = 1 n = len(nums) j = -1 ret = 0 for i in range(n): p *= nums[i] while p >= k and j < i: j += 1 p /= nums[j] if p < k: ret += i - j return ret<file_sep>func longestValidParentheses(s string) int { res := 0 valid := make([]int, len(s)) stack := []int{} for i := range s { if s[i] == '(' { stack = append(stack, i) } else if len(stack) > 0 { p := stack[len(stack)-1] if s[p] == '(' { stack = stack[:len(stack)-1] valid[i] = i - p + 1 if p > 0 { valid[i] += valid[p-1] } if valid[i] > res { res = valid[i] } } } } return res }<file_sep>class Solution(object): def romanToInt(self, s): """ :type s: str :rtype: int """ r2i = { 'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000 } ret = 0 for i in range(len(s)): if i+1<len(s) and r2i[s[i]] < r2i[s[i+1]]: ret -= r2i[s[i]] else: ret += r2i[s[i]] return ret <file_sep># Definition for a binary tree node. # class TreeNode # attr_accessor :val, :left, :right # def initialize(val) # @val = val # @left, @right = nil, nil # end # end # @param {TreeNode} t1 # @param {TreeNode} t2 # @return {TreeNode} def merge_trees(t1, t2) if t1 == nil and t2 == nil then return nil end val1, val2, l1, l2, r1, r2 = 0, 0, nil, nil, nil, nil if t1 != nil val1 = t1.val l1 = t1.left r1 = t1.right end if t2 != nil val2 = t2.val l2 = t2.left r2 = t2.right end root = TreeNode.new(val1 + val2) root.left = merge_trees(l1, l2) root.right = merge_trees(r1, r2) return root end<file_sep># Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def levelOrderBottom(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ ret = [] s1 = [] s2 = [] if root: s1.append(root) while len(s1) > 0: ret.append([]) for node in s1: ret[-1].append(node.val) if node.left: s2.append(node.left) if node.right: s2.append(node.right) s1, s2 = s2, [] return ret[::-1]<file_sep># Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution(object): def insert(self, intervals, newInterval): """ :type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval] """ if not intervals: return [newInterval] n = len(intervals) ret = [] i = 0 f = False while i < n: if (not f) and newInterval.start <= intervals[i].start: f = True start, end = newInterval.start, newInterval.end while i < n and intervals[i].start <= end: end = max(end, intervals[i].end) i += 1 if ret and start <= ret[-1].end: ret[-1].end = max(ret[-1].end, end) else: ret.append(Interval(start, end)) else: ret.append(intervals[i]) i+=1 if not f: if newInterval.start <= ret[-1].end: ret[-1].end = max(ret[-1].end, newInterval.end) else: ret.append(newInterval) return ret <file_sep>class Solution: def firstUniqChar(self, s: str) -> int: chars = [0] * 26 for c in s: chars[ord(c)-ord('a')] += 1 for i in range(len(s)): if chars[ord(s[i])-ord('a')] == 1: return i return -1<file_sep>func largestDivisibleSubset(nums []int) []int { n := len(nums) sort.Ints(nums) maxi, maxl := 0, 0 dp := make([]int, n) pre := make([]int, n) for i := 0; i < n; i++ { if dp[i] == 0 { dp[i] = 1 pre[i] = -1 } for j := i + 1; j < n; j++ { if nums[j]%nums[i] == 0 && dp[j] < dp[i]+1 { dp[j] = dp[i] + 1 pre[j] = i } } if dp[i] > maxl { maxl = dp[i] maxi = i } } res := make([]int, 0, maxl) for i := maxi; i >= 0; i = pre[i] { res = append(res, nums[i]) } return res } <file_sep>func countArrangement(n int) int { res := 0 used := make([]bool, n+1) var dfs func(i int) dfs = func(i int) { if i == n+1 { res++ return } for j := 1; j <= n; j++ { if !used[j] && (j%i == 0 || i%j == 0) { used[j] = true dfs(i + 1) used[j] = false } } } dfs(1) return res }<file_sep>class Solution(object): def arrangeCoins(self, n): """ :type n: int :rtype: int """ import math return int((-1 + math.sqrt(1+4*2*n))/2) <file_sep>class Solution(object): def canWinNim(self, n): """ :type n: int :rtype: bool """ return n<=3 or n%4!=0 <file_sep>class Solution(object): def findPoisonedDuration(self, timeSeries, duration): """ :type timeSeries: List[int] :type duration: int :rtype: int """ if not timeSeries: return 0 ret = 0 x = timeSeries[0] for i in timeSeries: y = i + duration if y > x: ret += min(y - x, duration) x = y return ret <file_sep># The guess API is already defined for you. # @param num, your guess # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 # def guess(num: int) -> int: class Solution: def guessNumber(self, n: int) -> int: l, r = 1, n while l <= r: m = (l + r) >> 1 k = guess(m) if k == -1: r = m - 1 elif k == 1: l = m + 1 else: return m return l<file_sep>class Solution: def fourSum(self, nums: List[int], target: int) -> List[List[int]]: nums.sort() n = len(nums) ret = [] for a in range(n): if a > 0 and nums[a] == nums[a-1]: continue for b in range(a+1, n): if b > a+1 and nums[b] == nums[b-1]: continue c, d = b+1, n-1 while c < d: x = nums[a] + nums[b] + nums[c] + nums[d] if x < target: c += 1 elif x > target: d -= 1 else: ret.append((nums[a], nums[b], nums[c], nums[d])) c += 1 d -= 1 while c < d and nums[c] == nums[c-1]: c += 1 while c < d and nums[d] == nums[d+1]: d -= 1 return ret<file_sep>class Solution: def isHappy(self, n: int) -> bool: nums = set() while n not in nums: nums.add(n) m = 0 while n > 0: x = n % 10 n //= 10 m += x * x n = m return n == 1<file_sep># Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reorderList(self, head: ListNode) -> None: """ Do not return anything, modify head in-place instead. """ nodes = [] while head: nodes.append(head) head = head.next n = len(nodes) i, j = 0, n-1 while i < j: nodes[i].next = nodes[j] nodes[j].next = nodes[i+1] i = i + 1 j = j - 1 nodes[i].next = None return nodes[0]<file_sep>class Solution(object): def findMaxConsecutiveOnes(self, nums): """ :type nums: List[int] :rtype: int """ ret=0 i=0 while i < len(nums): begin = i while i < len(nums) and nums[i] == 1: i += 1 ret = max(ret, i-begin) while i < len(nums) and nums[i] == 0: i += 1 return ret<file_sep>class Solution: def kthGrammar(self, n: int, k: int) -> int: if k <= 2: return k - 1 from math import log return self.kthGrammar(n, k-(1<<int(log(k-1)/log(2)))) ^ 1<file_sep>class Solution: def deleteAndEarn(self, nums: List[int]) -> int: from collections import defaultdict points = defaultdict(int) for num in nums: points[num] += num nums = list(points.keys()) nums.sort() n = len(nums) dp = [[0, 0] for i in range(n)] dp[0] = [0, points[nums[0]]] for i in range(1, n): dp[i][0] = max(dp[i-1][0], dp[i-1][1]) if nums[i-1] + 1 == nums[i]: dp[i][1] = dp[i-1][0] + points[nums[i]] else: dp[i][1] = dp[i][0] + points[nums[i]] return max(dp[-1]) <file_sep>class Solution(object): def nthUglyNumber(self, n): """ :type n: int :rtype: int """ ret = [1] f2, f3, f5 = 0, 0, 0 while len(ret) <n : minnum = min(ret[f2] * 2, ret[f3]*3, ret[f5] * 5) if minnum == ret[f2] * 2: f2 += 1 elif minnum == ret[f3]*3: f3 += 1 else: f5 += 1 if minnum > ret[-1]: ret.append(minnum) return ret[n-1] <file_sep>func calculate(s string) int { nums := make([]any, 0) n := len(s) for i := 0; i < n; i++ { if s[i] == ' ' { continue } if s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/' { nums = append(nums, s[i]) } else { num := 0 for i < n && s[i] >= '0' && s[i] <= '9' { num = num*10 + int(s[i]-'0') i++ } nums = append(nums, num) i-- } } nums2 := make([]any, 0) for i := 0; i < len(nums); i++ { if op, ok := nums[i].(uint8); ok && (op == '*' || op == '/') { a := nums2[len(nums2)-1].(int) b := nums[i+1].(int) if op == '*' { nums2[len(nums2)-1] = a * b } else { nums2[len(nums2)-1] = a / b } i++ } else { nums2 = append(nums2, nums[i]) } } nums = nums2 nums2 = make([]any, 0) for i := 0; i < len(nums); i++ { if op, ok := nums[i].(uint8); ok { a := nums2[len(nums2)-1].(int) b := nums[i+1].(int) if op == '+' { nums2[len(nums2)-1] = a + b } else { nums2[len(nums2)-1] = a - b } i++ } else { nums2 = append(nums2, nums[i]) } } return nums2[0].(int) } <file_sep># @param {Integer[]} gas # @param {Integer[]} cost # @return {Integer} def can_complete_circuit(gas, cost) start = gas.length - 1 pos = 0 left = gas[start] - cost[start] while start > pos if left >= 0 left += gas[pos] - cost[pos] pos += 1 else start -= 1 left += gas[start] - cost[start] end end return left >= 0 ? start : -1 end<file_sep>class Solution: def evaluate(self, s: str, knowledge: List[List[str]]) -> str: knowledge = dict(knowledge) ret = [] start = 0 i, n = 0, len(s) while i < n: if s[i] == '(': start = i + 1 while s[i] != ')': i += 1 ret.append(knowledge.get(s[start:i], '?')) else: ret.append(s[i]) i += 1 return ''.join(ret)<file_sep>class WordDictionary: def __init__(self): self.root = [False, {}] def addWord(self, word: str) -> None: node = self.root for c in word: if c not in node[1]: node[1][c] = [False, {}] node = node[1][c] node[0] = True def search(self, word: str) -> bool: length = len(word) q = [[0, self.root]] while len(q) > 0: i, node = q.pop() if i >= length: if node[0]: return True elif word[i] == '.': q += [[i+1, n] for n in node[1].values()] elif word[i] in node[1]: q.append([i+1, node[1][word[i]]]) return False # Your WordDictionary object will be instantiated and called as such: # obj = WordDictionary() # obj.addWord(word) # param_2 = obj.search(word)<file_sep>class Solution: def hIndex(self, citations: List[int]) -> int: n = len(citations) citations.sort() ret = 0 for i in range(n): if n-i >= citations[i]: ret = max(ret, citations[i]) else: ret = max(ret, n-i) return ret<file_sep>class Solution(object): def nextGreaterElements(self, nums): """ :type nums: List[int] :rtype: List[int] """ ret = [-1]*len(nums) st = [] for i in range(len(nums)): while len(st)>0 and nums[i] > nums[st[-1]]: ret[st.pop()] = nums[i] st.append(i) for i in range(len(nums)): while len(st)>0 and nums[i] > nums[st[-1]]: ret[st.pop()] = nums[i] return ret <file_sep>func firstMissingPositive(nums []int) int { n := len(nums) if n == 0 { return 1 } swap := func(i, j int) { nums[i], nums[j] = nums[j], nums[i] } for i := 0; i < n; i++ { for nums[i] > 0 && nums[i] <= n && i+1 != nums[i] && nums[i] != nums[nums[i]-1] { swap(i, nums[i]-1) } } for i := 0; i < n; i++ { if i+1 != nums[i] { return i + 1 } } return nums[n-1] + 1 }<file_sep>class Solution: def combinationSum3(self, k: int, n: int) -> List[List[int]]: ret = [] arr = [] def combination(s, x, y): if s == n and y == 0: ret.append(arr[:]) elif s < n and y>0 and 10-x >= y: combination(s, x+1, y) arr.append(x) combination(s+x, x+1, y-1) arr.pop() combination(0, 1, k) return ret<file_sep>class Solution: def leastInterval(self, tasks: List[str], n: int) -> int: m = len(tasks) count = {} maxt = 0 for t in tasks: count[t] = count.get(t, 0) + 1 maxt = max(maxt, count[t]) nt = 0 for t in count.values(): if t == maxt: nt += 1 res = (maxt-1) * (n + 1) + nt res = max(res, m) return res <file_sep>class Solution: def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int: n = len(difficulty) d = {} inf = float('inf') for i in range(n): d[profit[i]] = min(d.get(profit[i], inf), difficulty[i]) profit.sort() worker.sort(reverse=True) ret = 0 p = n - 1 for w in worker: while p >= 0 and w < d[profit[p]]: p -= 1 if p >= 0: ret += profit[p] return ret<file_sep>func maxSlidingWindow(nums []int, k int) []int { n := len(nums) res := make([]int, 0, n) slid := make([]int, n) l, r := 0, 0 for i := 0; i < n; i++ { if i >= k { if l < r && nums[i-k] == slid[l] { l++ } } for l < r && slid[r-1] < nums[i] { r-- } slid[r] = nums[i] r++ if i >= k-1 { res = append(res, slid[l]) } } return res } <file_sep>class Solution: def minAddToMakeValid(self, s: str) -> int: ret = 0 x = 0 for c in s: if c == '(': if x > 0: ret += x x = 0 x -= 1 else: x += 1 ret += abs(x) return ret <file_sep>class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: from functools import cmp_to_key def interval_cmp(a, b): if a[0] < b[0]: return -1 elif a[0] == b[0]: if a[1] < b[1]: return -1 elif a[1] == b[1]: return 0 else: return 1 else: return 1 intervals.sort(key=cmp_to_key(interval_cmp)) merged_intervals = [] last_interval = intervals[0] for interval in intervals[1:]: if interval[0] <= last_interval[1]: last_interval = [last_interval[0], max(last_interval[1], interval[1])] continue else: merged_intervals.append(last_interval) last_interval = interval merged_intervals.append(last_interval) return merged_intervals <file_sep>func compress(chars []byte) int { n := len(chars) if n <= 1 { return n } res := 0 cnt := 1 for i := 1; i <= n; i++ { if i == n || chars[i] != chars[i-1] { chars[res] = chars[i-1] res++ if cnt > 1 { s := strconv.Itoa(cnt) for j := 0; j < len(s); j++ { chars[res] = s[j] res++ } } cnt = 1 } else { cnt++ } } return res }<file_sep>class Solution: def minimumTotal(self, triangle: List[List[int]]) -> int: n = len(triangle) r1 = [triangle[0][0]] r2 = [0, 0] for i in range(1, n): r2[0] = triangle[i][0] + r1[0] r2[-1] = triangle[i][-1] + r1[-1] for j in range(1, i): r2[j] = triangle[i][j] + min(r1[j], r1[j-1]) r1 = r2 r2 = [0] * (i+2) return min(r1)<file_sep>class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: n = len(nums) if n == 0: return [] ret = [] start = 0 for i in range(1, n): if nums[i-1] + 1!= nums[i]: if nums[start] == nums[i-1]: ret.append(f'{nums[start]}') else: ret.append(f'{nums[start]}->{nums[i-1]}') start = i if nums[start] == nums[-1]: ret.append(f'{nums[start]}') else: ret.append(f'{nums[start]}->{nums[-1]}') return ret<file_sep>class Solution: def isValidSerialization(self, preorder: str) -> bool: nodes = preorder.split(',') nodes.reverse() n = len(nodes) if (n - 1) % 2 != 0: return False def isValid(): if len(nodes) == 0: return False if nodes.pop() == '#': return True return isValid() and isValid() return isValid() and len(nodes) == 0 <file_sep># Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def nextLargerNodes(self, head: ListNode) -> List[int]: ret = [] h = head q = [] while h: while len(q) > 0 and h.val > q[-1].val: q[-1].nexti = h.val q.pop() h.nexti = 0 q.append(h) h = h.next h = head while h: ret.append(h.nexti) h = h.next return ret<file_sep>class Solution(object): def minEatingSpeed(self, piles, H): """ :type piles: List[int] :type H: int :rtype: int """ low = 1 high = max(piles) ret = 0 s = sum(piles) while low <= high: k = (low + high) >> 1 k1 = k - 1 if (s + k1) // k > H: low = k + 1 continue h = 0 for p in piles: h += (p + k1) // k if h > H: break if h > H: low = k + 1 else: high = k - 1 ret = k return ret<file_sep>class Solution: def __init__(self, N: int, blacklist: List[int]): n = len(blacklist) m = N - n if m <= 100000: self.seq = [] black = set(blacklist) for i in range(N): if i not in black: self.seq.append(i) else: self.N = N self.black = set(blacklist) self.m = m def pick(self) -> int: if self.m <= 100000: return random.choice(self.seq) else: while 1: x = random.randint(0, self.N-1) if x not in self.black: return x # Your Solution object will be instantiated and called as such: # obj = Solution(N, blacklist) # param_1 = obj.pick()<file_sep>class Solution: def calculateMinimumHP(self, dungeon: List[List[int]]) -> int: m, n = len(dungeon), len(dungeon[0]) dp = [[0]*(n) for _ in range(m)] dp[m-1][n-1] = 1 - dungeon[m-1][n-1] for i in range(m-2, -1, -1): dp[i][n-1] = max(1, dp[i+1][n-1]) - dungeon[i][n-1] for i in range(n-2, -1, -1): dp[m-1][i] = max(1, dp[m-1][i+1]) - dungeon[m-1][i] for i in range(m-2, -1, -1): for j in range(n-2, -1, -1): dp[i][j] = max(1, min(dp[i+1][j], dp[i][j+1])) - dungeon[i][j] return max(1, dp[0][0]) <file_sep>class Solution: def countNicePairs(self, nums: List[int]) -> int: from collections import defaultdict def rev(num): return int(''.join(reversed(str(num)))) nums = [num - rev(num) for num in nums] count = defaultdict(int) ret = 0 for num in nums: ret += count[num] count[num] += 1 return ret % 1000000007 <file_sep>class Solution: def findTheDifference(self, s: str, t: str) -> str: s, t = list(s), list(t) s.sort() t.sort() n = len(s) for i in range(n): if s[i] != t[i]: return t[i] return t[-1]<file_sep>class Solution: def nextGreaterElements(self, nums: List[int]) -> List[int]: n = len(nums) ret = [-1] * n q = [] for i in range(0, 2*n): i = i % n while len(q) > 0 and nums[i] > nums[q[-1]]: ret[q.pop()] = nums[i] q.append(i) return ret <file_sep>class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ m, n = len(matrix), len(matrix[0]) firstRow, firstCol = False, False for i in range(m): for j in range(n): if i == 0 and matrix[i][j] == 0: firstRow = True if j == 0 and matrix[i][j] == 0: firstCol = True if i != 0 and j != 0 and matrix[i][j] == 0: matrix[i][0] = 0 matrix[0][j] = 0 for i in range(1, m): for j in range(1, n): if matrix[i][0] == 0 or matrix[0][j] == 0: matrix[i][j] = 0 if firstRow: for i in range(n): matrix[0][i] = 0 if firstCol: for i in range(m): matrix[i][0] = 0 <file_sep>class CombinationIterator: def __init__(self, characters: str, combinationLength: int): def _generator(chars, n, chars2, i, j): if j == combinationLength: yield ''.join(chars2) elif i < n and combinationLength - j <= n - i: chars2[j] = chars[i] for s in _generator(chars, n, chars2, i+1, j+1): yield s for s in _generator(chars, n, chars2, i+1, j): yield s self._generator = _generator(sorted(characters), len(characters), [''] * combinationLength, 0, 0) self._next = next(self._generator, None) def next(self) -> str: _next = self._next self._next = next(self._generator, None) return _next def hasNext(self) -> bool: return self._next != None # Your CombinationIterator object will be instantiated and called as such: # obj = CombinationIterator(characters, combinationLength) # param_1 = obj.next() # param_2 = obj.hasNext()<file_sep>func exist(board [][]byte, word string) bool { m, n := len(board), len(board[0]) visited := make([]int, m*n) var existHelper func(i, j, k int) bool existHelper = func(i, j, k int) bool { if i < 0 || i >= m || j < 0 || j >= n || visited[i*n+j] == 1 || board[i][j] != word[k] { return false } if k == len(word)-1 { return true } visited[i*n+j] = 1 if existHelper(i-1, j, k+1) || existHelper(i+1, j, k+1) || existHelper(i, j-1, k+1) || existHelper(i, j+1, k+1) { return true } else { visited[i*n+j] = 0 return false } } for i := 0; i < m; i++ { for j := 0; j < n; j++ { if board[i][j] == word[0] && existHelper(i, j, 0) { return true } } } return false } <file_sep> func jump(nums []int) int { min := func(a, b int) int { if a < b { return a } return b } n := len(nums) dp := make([]int, n) for i := 1; i < n; i++ { dp[i] = n } for i := 0; i < n; i++ { for j := min(i+nums[i], n-1); j > i; j-- { if dp[j] > dp[i]+1 { dp[j] = dp[i] + 1 } else { break } } } return dp[n-1] } <file_sep>class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ n = len(prices) if n < 2: return 0 dp = [0]*n for i in range(0, n-1): for j in range(i+1, n): if prices[j] > prices[i]: x = dp[i-2] if i-2>=0 else 0 dp[j] = max(dp[j], x+prices[j]-prices[i]) else: dp[j] = max(dp[j], dp[j-1]) return dp[n-1] <file_sep>class Solution: def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int: if obstacleGrid[0][0] == 1 or obstacleGrid[-1][-1] == 1: return 0 m, n = len(obstacleGrid), len(obstacleGrid[0]) paths = [[0 for j in range(n)] for i in range(m)] paths[0][0] = 1 for i in range(m): for j in range(n): if obstacleGrid[i][j] == 1: continue if i-1 >= 0: paths[i][j] += paths[i-1][j] if j-1 >= 0: paths[i][j] += paths[i][j-1] return paths[-1][-1]<file_sep>class Solution: def rob(self, nums: List[int]) -> int: n = len(nums) dp = [[0, 0] for i in range(n)] dp2 = [[0, 0] for i in range(n)] dp2[0][1] = nums[0] for i in range(1, n): dp[i][0] = max(dp[i-1][0], dp[i-1][1]) dp[i][1] = dp[i-1][0] + nums[i] dp2[i][0] = max(dp2[i-1][0], dp2[i-1][1]) if i != n - 1: dp2[i][1] = dp2[i-1][0] + nums[i] return max(*dp[-1], *dp2[-1])<file_sep>class Solution(object): def findLHS(self, nums): """ :type nums: List[int] :rtype: int """ d = {} for i in nums: d[i] = d.get(i, 0) + 1 ret = 0 for k, v in d.iteritems(): if k-1 in d: ret = max(ret, v+d[k-1]) if k+1 in d: ret = max(ret, v+d[k+1]) return ret <file_sep>class Solution: def isInterleave(self, s1: str, s2: str, s3: str) -> bool: n1, n2 ,n3 = len(s1), len(s2), len(s3) if n1 + n2 != n3: return False dp = [[False]*(n2+1) for _ in range(n1+1)] dp[0][0] = True for i in range(n1+1): for j in range(n2+1): if i > 0: dp[i][j] |= dp[i-1][j] and s1[i-1] == s3[i+j-1] if j > 0: dp[i][j] |= dp[i][j-1] and s2[j-1] == s3[i+j-1] return dp[n1][n2]<file_sep>class Solution: def findLength(self, A: List[int], B: List[int]) -> int: n1, n2 = len(A), len(B) dp = [[0]*(n2+1) for i in range(n1+1)] ret = 0 for i in range(n1): for j in range(n2): if A[i] == B[j]: dp[i+1][j+1] = max(dp[i][j]+1, dp[i+1][j+1]) ret = max(ret, dp[i+1][j+1]) return ret<file_sep>""" # Definition for a Node. class Node: def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): self.val = val self.left = left self.right = right self.next = next """ class Solution: def connect(self, root: 'Node') -> 'Node': q = [root] if root else [] while len(q) > 0: q2 = [] for node in q: if node.left: q2.append(node.left) if node.right: q2.append(node.right) for i in range(len(q)-1): q[i].next = q[i+1] q = q2 return root<file_sep>class Solution: def maximalRectangle(self, matrix: List[List[str]]) -> int: res = 0 rows, cols = len(matrix), len(matrix[0]) left = [[0] * (cols+1) for _ in range(rows)] for i in range(rows): for j in range(cols): if matrix[i][j] == "0": continue left[i][j] = left[i][j-1] + 1 width = left[i][j] for k in range(i, -1, -1): width = min(width, left[k][j]) res = max(res, width * (i-k+1)) return res<file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSymmetric(self, root: Optional[TreeNode]) -> bool: if not root: return True def getVal(node): if not node: return None return node.val def getNextLevel(nodes): ret = [] for node in nodes: if node: ret.append(node.left) ret.append(node.right) return ret q1, q2 =[root.left], [root.right] while len(q1) > 0 or len(q2) > 0: if len(q1) != len(q2): return False n = len(q1) for i in range(n): if getVal(q1[i]) != getVal(q2[-i-1]): return False q1, q2 = getNextLevel(q1), getNextLevel(q2) return True<file_sep>class Solution: def toHex(self, num: int) -> str: if num == 0: return "0" hexstr = "0123456789abcdef" if num < 0: num = (1<<32) + num ret = [] while num > 0: x = num % 16 ret.append(hexstr[x]) num = num // 16 ret.reverse() return "".join(ret) <file_sep>func countSegments(s string) int { ff := func(r rune) bool { return r == ' ' } return len(strings.FieldsFunc(s, ff)) }<file_sep># @param {Integer[]} nums # @return {Integer} def find_max_length(nums) h = {} diff=0 n = nums.length ret=0 for i in 0...n if nums[i]==0 diff -=1 else diff += 1 end if h[diff].nil? h[diff] = [i] else h[diff] << i end end if h.include? 0 ret=h[0][-1]+1 end h.each do |k, v| if v != nil && v.length > 1 && v[-1]-v[0] > ret ret=v[-1]-v[0] end end ret end<file_sep># Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def deleteNode(self, root, key): """ :type root: TreeNode :type key: int :rtype: TreeNode """ return self._remove(root, key) def _min(self, node): while node.left: node = node.left return node.val def _remove(self, node, key): if node is None: return None ret = node if key < node.val: node.left = self._remove(node.left, key) elif key > node.val: node.right = self._remove(node.right, key) else: if node.left and node.right: node.val = self._min(node.right) node.right = self._remove(node.right, node.val) elif node.left: ret = node.left elif node.right: ret = node.right else: ret = None return ret<file_sep>func isPalindrome(head *ListNode) bool { if head == nil || head.Next == nil { return true } var pre *ListNode = nil root := &ListNode{0, head} slow, fast := root, root for fast != nil && fast.Next != nil { fast = fast.Next.Next slow, pre, slow.Next = slow.Next, slow, pre } if fast != nil { slow, pre, slow.Next = slow.Next, slow, pre } else { slow = slow.Next } for slow != nil { if slow.Val != pre.Val { return false } slow, pre = slow.Next, pre.Next } return true } <file_sep>class Solution(object): def solve(self, board): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ m = len(board) if m == 0: return n = len(board[0]) if n == 0: return visited = [[False for j in range(n)] for i in range(m)] q = [] for i in range(m): if board[i][0] == 'O': q.append((i, 0)) if board[i][n-1] == 'O': q.append((i, n-1)) for j in range(n): if board[0][j] == 'O': q.append((0, j)) if board[m-1][j] == 'O': q.append((m-1, j)) while len(q) > 0: x,y=q.pop() if visited[x][y]: continue visited[x][y] = True for i, j in [[0, 1],[1, 0],[0, -1],[-1, 0]]: x2 = x+i y2 = y+j if (0 <= x2 < m) and (0<= y2 < n) and (board[x2][y2] == 'O') and (not visited[x2][y2]): q.append((x2, y2)) for i, row in enumerate(board): for j, col in enumerate(row): if board[i][j] == 'O' and (not visited[i][j]): board[i][j] = 'X' #return board <file_sep>class MapSum: def __init__(self): self._root = [{}, 0] def insert(self, key: str, val: int) -> None: node = self._root for c in key: if c not in node[0]: node[0][c] = [{}, 0] node = node[0][c] node[1] = val def sum(self, prefix: str) -> int: ret = 0 node = self._root for c in prefix: if c not in node[0]: return 0 node = node[0][c] q = [node] while len(q) > 0: node = q.pop() ret += node[1] q += node[0].values() return ret # Your MapSum object will be instantiated and called as such: # obj = MapSum() # obj.insert(key,val) # param_2 = obj.sum(prefix)<file_sep>class Solution(object): def isNumber(self, s): """ :type s: str :rtype: bool """ def test_frac(s): if not s: return True n = len(s) i=0 if s[i].isdigit(): while i < n and s[i].isdigit(): i += 1 if i==n: return True if s[i]=='e': return test_exp(s[i+1:]) elif s[i].lower()=='e': return test_exp(s[i+1:]) return s[i:].isspace() def test_exp(s): if not s: return False n=len(s) i=0 if i < n and s[i] in ['-', '+']: i += 1 if i == n or not s[i].isdigit(): return False while i <n and s[i].isdigit(): i += 1 return i==n or s[i:].isspace() s = str(s) n = len(s) i = 0 #skip lead white space while i < n and s[i].isspace(): i += 1 if i < n and s[i] in ['-', '+']: i += 1 if i < n and s[i].isdigit(): while i < n and s[i].isdigit(): i +=1 if i < n and s[i].lower() == 'e': return test_exp(s[i+1:]) elif i < n and s[i] == '.': return test_frac(s[i+1:]) else: return i==n or s[i:].isspace() elif i < n and s[i] == '.': i+=1 if i<n and s[i].isdigit(): return test_frac(s[i:]) return False <file_sep># Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def rotateRight(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ def getl(h): l = 0 while h: l += 1 h = h.next return l if head is None or k <=0: return head L = getl(head) k = k%L if k == 0 or L <= 1: return head x = L - k - 1 h = head while x > 0: x -= 1 h = h.next ret = h.next h.next = None h = ret while h.next: h = h.next h.next = head return ret <file_sep>class Trie: def __init__(self): self._root = [{}, False] def insert(self, word: str) -> None: node = self._root for c in word: if c not in node[0]: node[0][c] = [{}, False] node = node[0][c] node[1] = True def search(self, word: str) -> bool: node = self._root for c in word: if c not in node[0]: return False node = node[0][c] return node[1] def startsWith(self, prefix: str) -> bool: node = self._root for c in prefix: if c not in node[0]: return False node = node[0][c] q = [node] while len(q) > 0: node = q.pop() if node[1]: return True q.extend(node[0].values()) return False # Your Trie object will be instantiated and called as such: # obj = Trie() # obj.insert(word) # param_2 = obj.search(word) # param_3 = obj.startsWith(prefix)<file_sep>class Solution: def isAdditiveNumber(self, num: str) -> bool: n = len(num) if n < 3: return False def dfs(a, b, i): if i == n: return True c = str(a+b) if num[i:].startswith(c): return dfs(b, a+b, i+len(c)) return False for i in range(1, n): if num[0] == '0' and i > 1: break for j in range(i+1, n): if num[i] == '0' and j-i>1: break if dfs(int(num[:i]), int(num[i:j]), j): return True return False<file_sep>class Solution: def findErrorNums(self, nums: List[int]) -> List[int]: res = [0, 0] d = set() for num in nums: if num in d: res[0] = num else: d.add(num) for i in range(1, len(nums)+1): if i not in d: res[1] = i return res<file_sep># Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def pathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: List[List[int]] """ ret = [] def path(node, l, s): l.append(node.val) s -= node.val if node.left is None and node.right is None: if s == 0: ret.append(l[:]) else: if node.left: path(node.left, l, s) if node.right: path(node.right, l, s) l.pop() if root: path(root, [], sum) return ret<file_sep># @param {String} moves # @return {Boolean} def judge_circle(moves) u,d,l,r=0,0,0,0 moves.each_char do |m| case m when 'U' then u+=1 when 'D' then d+=1 when 'L' then l+=1 else r+=1 end end u==d && l==r end<file_sep>func spiralOrder(matrix [][]int) []int { m, n := len(matrix), len(matrix[0]) res := make([]int, 0, m*n) x0, y0, x1, y1 := 0, 0, m-1, n-1 x, y := 0, 0 for len(res) < cap(res) { if x0 == x1 && y0 == y1 { res = append(res, matrix[x0][y0]) break } for y < y1 && len(res) < cap(res) { res = append(res, matrix[x][y]) y++ } for x < x1 && len(res) < cap(res) { res = append(res, matrix[x][y]) x++ } for y > y0 && len(res) < cap(res) { res = append(res, matrix[x][y]) y-- } for x > x0 && len(res) < cap(res) { res = append(res, matrix[x][y]) x-- } x0, y0, x1, y1 = x0+1, y0+1, x1-1, y1-1 x, y = x0, y0 } return res } <file_sep>class Solution: def longestMountain(self, arr: List[int]) -> int: ret = 0 n = len(arr) up, down = 0, 0 for i in range(1, n): if arr[i] > arr[i-1]: down = 0 up += 1 elif arr[i] < arr[i-1]: down += 1 if up > 0: ret = max(ret, up + down + 1) if i+1 < n and arr[i] <= arr[i+1]: up, down = 0,0 else: up, down = 0, 0 return ret <file_sep>class Solution: def findTargetSumWays(self, nums: List[int], target: int) -> int: from collections import defaultdict sums = defaultdict(int) sums[0] = 1 for num in nums: new_sums = defaultdict(int) for key, val in sums.items(): new_sums[key+num] += val new_sums[key-num] += val sums = new_sums return sums[target]<file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool: q = [] if root: q = [(root, root.val)] while len(q) > 0: q2 = [] for node, val in q: if (val == targetSum) and (not node.left) and (not node.right): return True if node.left: q2.append((node.left, val+node.left.val)) if node.right: q2.append((node.right, val+node.right.val)) q = q2 return False<file_sep>class Solution: def maxProduct(self, nums: List[int]) -> int: n = len(nums) dp = [[0, 0] for i in range(n+1)] dp[-1][0] = dp[-1][1] = 1 ret = nums[0] for i in range(n): dp[i][0] = max(nums[i], dp[i-1][0] * nums[i], dp[i-1][1] * nums[i]) dp[i][1] = min(nums[i], dp[i-1][0] * nums[i], dp[i-1][1] * nums[i]) ret = max(ret, dp[i][0], dp[i][1]) return ret <file_sep>class Solution: def maxScoreSightseeingPair(self, A: List[int]) -> int: ret = 0 n = len(A) i = 0 for j in range(1, n): ret = max(ret, A[i] + A[j] + i - j) if A[j] + j >= A[i] + i: i = j return ret<file_sep>class Solution: def countSmaller(self, nums: List[int]) -> List[int]: minNum, maxNum = min(nums), max(nums) delta = 0 if minNum <= 0: delta = abs(minNum) + 1 m = maxNum + delta n = len(nums) for i in range(n): nums[i] += delta c = [0] * (m + 1) counts = [0] * n for i in range(n-1, -1, -1): num = nums[i] while num <= m: c[num] += 1 num += -num&num num = nums[i]-1 count = 0 while num > 0: count += c[num] num -= -num&num counts[i] = count return counts<file_sep>class Solution(object): def longestIncreasingPath(self, matrix): """ :type matrix: List[List[int]] :rtype: int """ from copy import deepcopy if not matrix: return 0 m = len(matrix) n = len(matrix[0]) inx = [[0] * n for i in range(m)] out = [[0] * n for i in range(m)] cnt = [[1] * n for i in range(m)] for i in range(m): for j in range(n): if i-1>=0 and matrix[i][j] < matrix[i-1][j]: inx[i-1][j] += 1 out[i][j] += 1 if i+1<m and matrix[i][j] < matrix[i+1][j]: inx[i+1][j] += 1 out[i][j] += 1 if j-1>=0 and matrix[i][j] < matrix[i][j-1]: inx[i][j-1] += 1 out[i][j] += 1 if j+1<n and matrix[i][j] < matrix[i][j+1]: inx[i][j+1] += 1 out[i][j] += 1 q1 = [] for i in range(m): for j in range(n): if inx[i][j] == 0: q1.append([i, j]) ret = 0 while len(q1) > 0: t = q1.pop() i, j = t ret = max(ret, cnt[i][j]) if i-1>=0 and matrix[i][j] < matrix[i-1][j]: inx[i-1][j] -= 1 if inx[i-1][j] == 0: q1.append([i-1, j]) cnt[i-1][j] = max(cnt[i-1][j], cnt[i][j]+1) if i+1<m and matrix[i][j] < matrix[i+1][j]: inx[i+1][j] -= 1 if inx[i+1][j]==0: q1.append([i+1, j]) cnt[i+1][j] = max(cnt[i+1][j], cnt[i][j]+1) if j-1>=0 and matrix[i][j] < matrix[i][j-1]: inx[i][j-1] -= 1 if inx[i][j-1]==0: q1.append([i, j-1]) cnt[i][j-1] = max(cnt[i][j-1], cnt[i][j]+1) if j+1<n and matrix[i][j] < matrix[i][j+1]: inx[i][j+1] -= 1 if inx[i][j+1]==0: q1.append([i,j+1]) cnt[i][j+1] = max(cnt[i][j+1], cnt[i][j]+1) return ret <file_sep>class Solution: def shipWithinDays(self, weights: List[int], D: int) -> int: def ship(W, C, D): d = 1 c = 0 for w in W: if w > C or d > D: return False elif c + w <= C: c += w else: c = w d += 1 return d <= D l, r, m = 0, sum(weights), 0 while l < r: m = (l + r) >> 1 if ship(weights, m, D): r = m else: l = m + 1 return r <file_sep>class Solution(object): def lenLongestFibSubseq(self, A): """ :type A: List[int] :rtype: int """ set_a = set(A) n = len(A) dp = {} for a in A: dp[a] = {} ret = 0 for i in range(1, n): z = A[i] for j in range(i-1, -1, -1): y = A[j] x = z - y if x >= y: break if x in set_a: dp[y][z] = max(dp[y].get(z, 0), dp[x].get(y, 2)+1) ret = max(ret, dp[y][z]) return ret <file_sep>class Solution: def totalHammingDistance(self, nums: List[int]) -> int: diff = 0 n = len(nums) bit_map = {} for num in nums: while num > 0: bit = num & (-num) bit_map[bit] = bit_map.get(bit, 0) + 1 num -= bit for bit_count in bit_map.values(): diff += bit_count * (n - bit_count) return diff<file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def minDepth(self, root: TreeNode) -> int: if not root: return 0 q = [(root, 1)] while len(q) > 0: q2 = [] for node, d in q: if not node: continue if (not node.left) and (not node.right): return d q2.append((node.left, d+1)) q2.append((node.right, d+1)) q = q2<file_sep>class Solution: def validIPAddress(self, queryIP: str) -> str: import re def isV4(): v4 = r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$" if not re.match(v4, queryIP): return False groups = queryIP.split(".") for group in groups: if group[0] == "0" and len(group) > 1: return False if int(group) > 255: return False return True def isV6(): v6 = r"^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$" return re.match(v6, queryIP) != None if isV4(): return "IPv4" elif isV6(): return "IPv6" return "Neither"<file_sep>class Solution: def isAnagram(self, s: str, t: str) -> bool: a = [0] * 26 b = [0] * 26 orda = ord('a') for c in s: a[ord(c) - orda] += 1 for c in t: b[ord(c) - orda] += 1 return a == b<file_sep>class Solution: def minFlipsMonoIncr(self, S: str) -> int: n = len(S) num0 = S.count('0') num1 = S.count('1') ret = min(num0, num1) n0, n1 = 0, 0 for i in range(n): if S[i] == '0': n0 += 1 else: n1 += 1 ret = min(ret, n1 + num0 - n0) return ret <file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def addOneRow(self, root: TreeNode, val: int, depth: int) -> TreeNode: if depth == 1: node = TreeNode(val, root) return node row = [root] while depth > 2: row2 = [] for node in row: if node.left: row2.append(node.left) if node.right: row2.append(node.right) row = row2 depth -= 1 for node in row: left,right = node.left, node.right node.left = TreeNode(val, left) node.right = TreeNode(val, None, right) return root <file_sep>func splitArray(nums []int, k int) int { n := len(nums) sum := make([]int, n+1) for i := 0; i < n; i++ { sum[i+1] = sum[i] + nums[i] } check := func(x int) bool { cnt := 1 startIndex := 0 for i := 1; i <= n; i++ { if nums[i-1] > x { return false } if sum[i]-sum[startIndex] > x { cnt++ startIndex = i - 1 } } return cnt <= k } l, r := sum[n]/k, sum[n] for l < r { m := (l + r) / 2 if !check(m) { l = m + 1 } else { r = m } } return l }<file_sep>class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ if not matrix: return matrix n = len(matrix) k = 0 while k*2 < n: ret = [matrix[k][i + k] for i in range(n - 2 * k)] ret2 = [matrix[i + k][n - 1 - k] for i in range(n - 2 * k)] ret3 = [matrix[n - 1 - k][n - 1 - k - i] for i in range(n - 2 * k)] print ret, ret2, ret3 for i in range(n - 2 * k): matrix[k][i + k] = matrix[n - 1 - k - i][k] for i in range(n - 2 * k): matrix[i + k][n - 1 - k] = ret[i] for i in range(n - 2 * k): matrix[n - 1 - k][n - 1 - k - i] = ret2[i] for i in range(n - 2 * k): matrix[n - 1 - k - i][k] = ret3[i] k += 1 <file_sep>class Solution: def arrangeCoins(self, n: int) -> int: l, r = 1, 1<<31 while l < r: m = (l + r) // 2 if m*(m+1)//2 > n: r = m else: l = m + 1 return r-1<file_sep>class Solution: def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int: res = 0 mod = 10**9 + 7 moves = ((1, 0), (-1, 0), (0, 1), (0, -1)) dp = [[[0] *n for _ in range(m)] for _ in range(maxMove+1)] dp[0][startRow][startColumn] = 1 for k in range(maxMove): for i in range(m): for j in range(n): for x, y in moves: x, y = x+i, y+j if x <0 or x>=m or y<0 or y>=n: res = (res + dp[k][i][j]) % mod else: dp[k+1][x][y] = (dp[k+1][x][y] + dp[k][i][j]) % mod return res<file_sep>/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func maxPathSum(root *TreeNode) int { ret := math.MinInt32 max := func(a, b int) int { if a < b { return b } return a } var dfs func(node *TreeNode) int dfs = func(node *TreeNode) int { if node == nil { return math.MinInt32 } left := max(node.Val, node.Val+dfs(node.Left)) right := max(node.Val, node.Val+dfs(node.Right)) ret = max(ret, left+right-node.Val) return max(left, right) } dfs(root) return ret }<file_sep>class Solution: def canPartition(self, nums: List[int]) -> bool: n = len(nums) total_sum = sum(nums) if n < 2 or total_sum & 1 == 1: return False target = total_sum // 2 subsets = set([0]) for num in nums: new_subsets = [] for sub in subsets: new_sub = sub + num if new_sub == target: return True if new_sub not in subsets and new_sub < target: new_subsets.append(new_sub) subsets.update(new_subsets) return False <file_sep># Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def findSecondMinimumValue(self, root): """ :type root: TreeNode :rtype: int """ if (not root) or (not root.left): return -1 def find(v, r): if r.val > v: return r.val elif r.left: x = find(v, r.left) y = find(v, r.right) if x==-1: return y elif y==-1: return x return min(x, y) else: return -1 return find(root.val, root) <file_sep>class Solution: def plusOne(self, digits: List[int]) -> List[int]: if digits[-1] < 9: digits[-1] += 1 return digits digits.reverse() n = len(digits) digits[0] += 1 i = 0 while digits[i] > 9: digits[i] = digits[i] % 10 i += 1 if i == n: digits.append(0) digits[i] += 1 digits.reverse() return digits <file_sep>class Solution: def multiply(self, num1: str, num2: str) -> str: num1 = [int(i) for i in num1[::-1]] num2 = [int(i) for i in num2[::-1]] n1, n2 = len(num1), len(num2) num3 = [0] * (n1 + n2) for i in range(n1): k = 0 for j in range(n2): k += num3[i+j] + num1[i] * num2[j] num3[i+j] = k%10 k //= 10 num3[i+n2] = k i = n1 + n2 - 1 while i >= 0 and num3[i]==0: i -= 1 if i == -1: return '0' return ''.join([str(j) for j in num3[:i+1][::-1]]) <file_sep>func convert(s string, numRows int) string { n := len(s) if n <= numRows || numRows == 1 { return s } m := numRows*2 - 2 res := make([]byte, 0, n) for i := 0; i < numRows; i++ { for j := i; j < n; j += m { res = append(res, s[j]) if i != 0 && i != numRows-1 && j+m-2*i < n { res = append(res, s[j+m-2*i]) } } } return string(res) }<file_sep># Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def oddEvenList(self, head: ListNode) -> ListNode: if (not head) or (not head.next): return head r1, r2 = ListNode(0), ListNode(0) h1, h2 = r1, r2 while head: h1.next = head h2.next = head.next h1 = h1.next h2 = h2.next head = head.next.next if head.next else None h1.next = r2.next return r1.next <file_sep>class Solution(object): def findRepeatedDnaSequences(self, s): """ :type s: str :rtype: List[str] """ b = 31 B = 1 for i in range(10): B *= b h = 0 for c in s[:10]: h = h * b + ord(c) d = { h: [9] } ret = set() for i, c in enumerate(s[10:], 10): h = h * b + ord(c) - ord(s[i-10]) * B x = h #print x if x in d: f = False for y in d[x]: if s[y - 9: y + 1] == s[i - 9: i + 1]: f = True ret.add(y) break if not f: d[x].append(i) else: d[x] = [i] return [s[i - 9: i + 1] for i in ret] <file_sep>class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: n, m = len(grid), len(grid[0]) row = [max(r) for r in grid] col = [0] * m for j in range(m): for i in range(n): col[j] = max(col[j], grid[i][j]) ret = 0 for i in range(n): for j in range(m): ret += max(0, min(row[i], col[j]) - grid[i][j]) return ret <file_sep>class Solution: def customSortString(self, order: str, s: str) -> str: return ''.join(sorted(list(s), key=lambda x: order.index(x) if x in order else -1))<file_sep>class Solution: def replaceWords(self, dict: List[str], sentence: str) -> str: ret = [] dict.sort(key=lambda x: len(x)) for word in sentence.split(' '): r = word for root in dict: if word.startswith(root): r = root break ret.append(r) return ' '.join(ret)<file_sep>class Solution: def findRadius(self, houses: List[int], heaters: List[int]) -> int: houses = houses + heaters houses.sort() heaters = set(heaters) n = len(houses) left, right = [-1] * n, [-1] * n l, r = min(heaters), max(heaters) for i in range(n): if houses[i] in heaters: l = houses[i] else: left[i] = l if houses[-i] in heaters: r = houses[-i] else: right[-i] = r ret = 0 for i in range(n): if houses[i] in heaters: continue h = houses[i] x, y = abs(h - left[i]), abs(h-right[i]) ret = max(ret, min(x, y)) return ret <file_sep># Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def rob(self, root): """ :type root: TreeNode :rtype: int """ return self._rob(root, True) def _rob(self, root, canbuy): if root is None: return 0 ret = 0 if canbuy: buy, nobuy = 0, 0 if hasattr(root, 'buy'): buy = root.buy else: buy = root.val + self._rob(root.left, False) + self._rob(root.right, False) root.buy = buy if hasattr(root, 'nobuy'): nobuy = root.nobuy else: nobuy = self._rob(root.left, True) + self._rob(root.right, True) root.nobuy = nobuy ret = max(buy, nobuy) else: ret = self._rob(root.left, True) + self._rob(root.right, True) return ret <file_sep>class Solution: def canJump(self, nums: List[int]) -> bool: n = len(nums) ans = [False] * n ans[0] = True m = 0 for i in range(n): if not ans[i]: return False for j in range(m, min(n, i + nums[i]+1)): ans[j] = True m = max(m, i + nums[i]+1) return ans[-1] <file_sep>class Solution: def numDecodings(self, s: str) -> int: if s.startswith('0'): return 0 n = len(s) dp = [0] *(n + 2) dp[-1] = dp[-2] = 1 for i in range(n): if s[i] != '0': dp[i] += dp[i-1] if i > 0 and s[i-1] != '0' and int(s[i-1:i+1]) <= 26: dp[i] += dp[i-2] return dp[i]<file_sep>class Solution(object): def findLongestChain(self, pairs): """ :type pairs: List[List[int]] :rtype: int """ if not pairs: return 0 def cmp(a, b): if a[0] != b[0]: return a[0]-b[0] return a[1]-b[1] pairs.sort(cmp=cmp) n = len(pairs) dp = [1] * n for i in xrange(n): for j in xrange(i): if pairs[j][1] < pairs[i][0] and dp[j]+1>dp[i]: dp[i] = dp[j]+1 return max(dp) <file_sep># @param {Integer[][]} matrix # @return {Void} Do not return anything, modify matrix in-place instead. def set_zeroes(matrix) m = matrix.length n = matrix[0].length row, col = false, false for i in 0...m for j in 0...n if matrix[i][j] == 0 matrix[i][0] = 0 matrix[0][j] = 0 if i==0 then row=true end if j==0 then col=true end end end end for i in 1...m for j in 1...n matrix[i][j] = 0 if matrix[i][0]==0 || matrix[0][j]==0 end end if row for j in 0...n matrix[0][j]=0 end end if col for i in 0...m matrix[i][0]=0 end end end<file_sep>class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: n = len(rooms) visited = [0] * n keys = [0] while len(keys) > 0: key = keys.pop() if visited[key] == 1: continue visited[key] = 1 keys.extend(rooms[key]) return sum(visited) == n<file_sep>class Solution: def arrayNesting(self, nums: List[int]) -> int: n = len(nums) m, k = 0, 0 dp = [0] * n for i in range(n): if dp[i] > 0: continue s = set() j = i while not (j in s): s.add(j) j = nums[j] l = len(s) + dp[j] for x in s: dp[x] = l return max(dp)<file_sep>class RandomizedSet: def __init__(self): self.items = [] self.set = {} self.unused = [] def insert(self, val: int) -> bool: if val in self.set: return False if len(self.unused) > 0: i = self.unused.pop() self.set[val] = i self.items[i] = val else: i = len(self.items) self.set[val] = i self.items.append(val) return True def remove(self, val: int) -> bool: if val in self.set: i = self.set[val] del self.set[val] self.unused.append(i) self.items[i] = None if len(self.unused) * 4 > len(self.items): self.items = list(filter(lambda x: x!=None, self.items)) self.unused = [] self.set = {} for i in range(len(self.items)): self.set[self.items[i]] = i return True return False def getRandom(self) -> int: import random while True: x = random.choice(self.items) if x != None: return x # Your RandomizedSet object will be instantiated and called as such: # obj = RandomizedSet() # param_1 = obj.insert(val) # param_2 = obj.remove(val) # param_3 = obj.getRandom()<file_sep>class Solution: def subarraySum(self, nums: List[int], k: int) -> int: n = len(nums) sums = {} ret = 0 sum = 0 for i in range(n): sum += nums[i] x = sum - k if sum == k: ret += 1 ret += sums.get(x, 0) sums[sum] = sums.get(sum, 0) + 1 return ret <file_sep>class Solution: def rangeBitwiseAnd(self, left: int, right: int) -> int: ret = right x = right while x > 0: y = x & (-x) if left & y == 0 or right -y >= left: ret -= y x -= y return ret <file_sep>class Solution: def findPairs(self, nums: List[int], k: int) -> int: from collections import defaultdict count = defaultdict(int) nums.sort() for num in nums: count[num] += 1 ret = 0 for num in sorted(count.keys()): if k == 0 and count[num] > 1: ret += 1 elif k > 0 and num + k in count: ret += 1 elif k < 0 and num - k in count: ret += 1 return ret<file_sep>class Solution: def topKFrequent(self, words: List[str], k: int) -> List[str]: from collections import defaultdict from functools import cmp_to_key def cmp(a, b): if a[1] != b[1]: return a[1]-b[1] elif a[0] < b[0]: return 1 return -1 top = defaultdict(int) for w in words: top[w] += 1 return [w[0] for w in sorted(top.items(), key=cmp_to_key(cmp), reverse=True)[:k]]<file_sep>class Solution: def __init__(self, m: int, n: int): self._m = m self._n = n self._matrix = [set() for _ in range(m)] def flip(self) -> List[int]: from random import randint m, n = self._m, self._n row = randint(0, m-1) while len(self._matrix[row]) == n: row = (row + 1) % m s = self._matrix[row] col = randint(0, n-1) while col in s: col = (col + 1) % n s.add(col) return [row, col] def reset(self) -> None: for s in self._matrix: s.clear() # Your Solution object will be instantiated and called as such: # obj = Solution(m, n) # param_1 = obj.flip() # obj.reset()<file_sep>class Solution: def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int: count = 0 sum12 = {} for i in nums1: for j in nums2: sum12[i+j] = sum12.get(i+j, 0)+1 for i in nums3: for j in nums4: k = 0 - i - j count += sum12.get(k, 0) return count<file_sep>class Solution: def isPowerOfFour(self, n: int) -> bool: return n == 1 or (n > 0 and -n&n == n and n%10 in [4, 6])<file_sep>class Solution: def largestNumber(self, nums: List[int]) -> str: from functools import cmp_to_key nums = [str(num) for num in nums] def cmp(a, b): if a == b: return 0 if a + b > b + a: return -1 return 1 nums.sort(key=cmp_to_key(cmp)) if nums[0] == '0': return '0' return ''.join(nums) <file_sep>from random import random from math import sqrt class Solution: def __init__(self, radius: float, x_center: float, y_center: float): self.radius = radius self.x = x_center self.y = y_center def randPoint(self) -> List[float]: while True: x, y = [random()*self.radius*2 + self.x - self.radius, random()*self.radius*2 + self.y - self.radius] if sqrt((x-self.x) * (x-self.x) + (y-self.y)*(y-self.y)) <= self.radius: return [x, y] # Your Solution object will be instantiated and called as such: # obj = Solution(radius, x_center, y_center) # param_1 = obj.randPoint()<file_sep>class Solution: def canReorderDoubled(self, arr: List[int]) -> bool: from collections import defaultdict d = defaultdict(int) n = len(arr) arr.sort() ret = 0 for num in arr: if num > 0 and num&1 == 0: num2 = num // 2 else: num2 = num * 2 if d.get(num2, 0) > 0: d[num2] -= 1 ret += 1 else: d[num] += 1 #print(ret, arr) return ret == n//2 <file_sep>class Solution(object): def findRelativeRanks(self, nums): """ :type nums: List[int] :rtype: List[str] """ nums2 = sorted(nums, reverse=True) top = {} for i in range(len(nums2)): top[nums2[i]] = i+1 ret = [] for i in nums: if top[i] == 1: ret.append('Gold Medal') elif top[i] == 2: ret.append('Silver Medal') elif top[i] == 3: ret.append('Bronze Medal') else: ret.append(str(top[i])) return ret <file_sep># Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def removeZeroSumSublists(self, head): """ :type head: ListNode :rtype: ListNode """ def list2arr(node): arr = [] while node: arr.append(node.val) node = node.next return arr def arr2list(arr): head = ListNode(0) h = head for i in arr: h.next = ListNode(i) h = h.next return head.next arr = list2arr(head) n = len(arr) s = [0] * n s[0] = arr[0] index = {s[0]: [0]} for i in range(1, n): s[i] = s[i-1] + arr[i] if s[i] in index: index[s[i]].append(i) else: index[s[i]] = [i] print(s) arr2 = [] i = max(index.get(0, [-1])) + 1 while i < n: if arr[i] == 0: i += 1 continue j = max(index.get(s[i], [0])) arr2.append(arr[i]) if i < j: i = j + 1 else: i += 1 return arr2list(arr2) <file_sep>class Solution: def __init__(self, w: List[int]): n = len(w) ws = [0] * n ws[0] = w[0] for i in range(1, n): ws[i] = ws[i-1] + w[i] self.n = n self.ws = ws def pickIndex(self) -> int: from random import randint x = randint(1, self.ws[-1]) l, r = 0, self.n while l < r: m = (l + r) >> 1 if x <= self.ws[m]: r = m else: l = m + 1 return r # Your Solution object will be instantiated and called as such: # obj = Solution(w) # param_1 = obj.pickIndex()<file_sep>class Solution(object): def divide(self, dividend, divisor): """ :type dividend: int :type divisor: int :rtype: int """ if dividend ==0: return 0 flag= 1 if (dividend < 0 and divisor > 0) or (dividend > 0 and divisor < 0): flag = -1 dividend = abs(dividend) divisor = abs(divisor) d = {} for i in range(32): d[1<<i] = i f = [] while divisor: x=divisor &(-divisor) f.append(d[x]) divisor -=x l = 0 r = dividend ret = 0 while l<=r: m = (l + r) >> 1 k = sum([m << i for i in f]) if k <= dividend: l = m + 1 ret = m else: r = m - 1 if flag == -1: ret = -fet return min(ret, (1<<31)-1) <file_sep>func grayCode(n int) []int { res := []int{0, 1} for i := 1; i < n; i++ { for j := len(res) - 1; j >= 0; j-- { res = append(res, res[j]|(1<<i)) } } return res }<file_sep>class Solution: def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]: f = {} groups = {} names = {} def getf(email): while email != f.get(email, email): email = f[email] return email for account in accounts: name = account[0] root = getf(account[1]) for email in account[1:]: f[getf(email)] = root names[email] = name for email in f.keys(): group = getf(email) if group not in groups: groups[group] = [names[group]] groups[group].append(email) ret = [] for group in groups.values(): ret.append([group[0]] + sorted(group[1:])) return ret <file_sep>class Solution: def maxProfit(self, prices: List[int]) -> int: minp = prices[0] ret = 0 for price in prices: minp = min(minp, price) ret = max(ret, price-minp) return ret<file_sep>class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: n = len(gas) dp = [gas[i]-cost[i] for i in range(n)] if sum(dp) < 0: return -1 ret = 0 x = 0 for i in range(n): x += dp[i] if x < 0: x = 0 ret = i + 1 return ret <file_sep>class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: n = len(nums) ret = nums[:] for i in range(1, n): nums[i] *= nums[i-1] ret[-i-1] *= ret[-i] ret[0] = ret[1] for i in range(1, n-1): ret[i] = nums[i-1] * ret[i+1] ret[-1] = nums[-2] return ret<file_sep>class Solution: def partition(self, s: str) -> List[List[str]]: n = len(s) ispalindrome = [[True]*n for _ in range(n)] for j in range(n): for i in range(j-1, -1, -1): ispalindrome[i][j] = s[i] == s[j] and ispalindrome[i+1][j-1] res = [] parts = [] def dfs(i): if i == n: res.append(parts[:]) return for j in range(i, n): if ispalindrome[i][j]: parts.append(s[i:j+1]) dfs(j+1) parts.pop() dfs(0) return res <file_sep>class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ y = abs(x) ret = 0 while y != 0: ret = ret * 10 + y % 10 y /= 10 if x < 0: ret = -ret if ret > 0x7fffffff or ret < -0x80000000: return 0 return ret <file_sep>class Solution(object): def jump(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) step = [-1] * (n) step[0] = 0 for i, s in enumerate(nums): j = min(i + s, n - 1) if step[j] == -1 or step[i] + 1 < step[j]: step[j] = step[i] + 1 for k in range(i+1, j): if step[k] == -1 or step[i] + 1 < step[k]: step[k] = step[i] + 1 return step[-1] <file_sep># Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ ret = [True] def balance(node): if node is None: return 0 lh = balance(node.left) rh = balance(node.right) if abs(lh - rh) > 1: ret[0] = False return max(lh, rh) + 1 balance(root) return ret[0] <file_sep>func findMaxForm(strs []string, m int, n int) int { max := func(x, y int) int { if x < y { return y } return x } k := len(strs) dp := make([][]int, m+1) for i := 0; i < m+1; i++ { dp[i] = make([]int, n+1) } for i := 0; i < k; i++ { zero := 0 one := 0 for _, v := range strs[i] { if v == '0' { zero++ } else { one++ } } for x := m; x >= 0; x-- { for y := n; y >= 0; y-- { if x >= zero && y >= one { dp[x][y] = max(dp[x][y], dp[x-zero][y-one]+1) } if x > 0 { dp[x][y] = max(dp[x][y], dp[x-1][y]) } if y > 0 { dp[x][y] = max(dp[x][y], dp[x][y-1]) } } } } return dp[m][n] } <file_sep># Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: h1, h2 = l1, l2 while h1 and h2: h1, h2 = h1.next, h2.next res = [0] while h1: res.append(l1.val) h1, l1 = h1.next, l1.next while h2: res.append(l2.val) h2, l2 = h2.next, l2.next while l1: res.append(l1.val + l2.val) l1, l2 = l1.next, l2.next res.reverse() n = len(res) for i in range(n-1): if res[i] > 9: res[i+1] += 1 res[i] = res[i] % 10 if res[-1] == 0: res.pop() h = None for num in res: h = ListNode(num, h) return h <file_sep>class Solution: def countNumbersWithUniqueDigits(self, n: int) -> int: from functools import reduce def countN(x): if x == 0: return 1 if x == 1: return 9 return reduce(lambda x, y: x * (9-y), range(x-1), 9) return reduce(lambda x, y: x + countN(y), range(n+1), 0) <file_sep># Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def insertionSortList(self, head: ListNode) -> ListNode: def insert(root, node): if node.val <= root.val: node.next = root return node n1, n2 = root, root.next while n2 and node.val > n2.val: n1 = n1.next n2 = n2.next n1.next = node node.next = n2 return root root, n1, n2 = head, head, head.next while n2: if n1.val > n2.val: n1.next = n2.next root = insert(root, n2) n2 = n1.next else: n1 = n1.next n2 = n2.next return root<file_sep>class Solution: def pathInZigZagTree(self, label: int) -> List[int]: def get_f(val): if val <= 1: return val n = 1 while (2 ** n) - 1 < val: n += 1 n_end = (2 ** n) - 1 n_begin = n_end - (2 ** (n - 1)) + 1 return (n_end - (val - n_begin)) // 2 ret = [label] while ret[-1] != 1: ret.append(get_f(ret[-1])) ret.reverse() return ret <file_sep>class Solution: def findContentChildren(self, g: List[int], s: List[int]) -> int: g.sort(reverse=True) s.sort(reverse=True) ret = 0 while len(g) > 0 and len(s) > 0: while len(s) > 0 and s[-1] < g[-1]: s.pop() if len(s) > 0 and s[-1] >= g[-1]: g.pop() s.pop() ret += 1 return ret <file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def lcaDeepestLeaves(self, root: TreeNode) -> TreeNode: def get_depth(node): if node is None: return 0 return 1 + max(get_depth(node.left), get_depth(node.right)) depth = get_depth(root) def get_lca(node, d): if node: if d == depth: return node else: l,r = get_lca(node.left, d+1), get_lca(node.right, d+1) if l and r: return node elif l: return l elif r: return r return None node = get_lca(root, 1) return node<file_sep>class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: res = [] n = len(nums) for i in range(n): j, k = i, nums[i]-1 while j+1 != nums[j] and k+1 != nums[k]: nums[j], nums[k] = nums[k], nums[j] k = nums[j] - 1 for i in range(n): if nums[i] != i+1: res.append(i+1) return res<file_sep>class Solution: def readBinaryWatch(self, turnedOn: int) -> List[str]: ret = [] def bitCount(h, m): count = 0 while h>0: count+=1 h -= -h&h while m > 0: count+=1 m -= -m&m return count for h in range(12): for m in range(60): if bitCount(h, m) == turnedOn: ret.append("{h}:{m:02d}".format(h=h,m=m)) return ret<file_sep>class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: n1 = len(text1) n2 = len(text2) dp = [[0]*(n2 + 1) for i in range(n1 + 1)] for i in range(n1): for j in range(n2): if text1[i] == text2[j]: dp[i+1][j+1] = max(dp[i][j] + 1, dp[i+1][j+1]) else: dp[i+1][j+1] = max(dp[i+1][j+1], dp[i+1][j], dp[i][j+1]) return dp[n1][n2]<file_sep># Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def pathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: int """ def path(root, sums): if root is None: return 0 ret = sums.count(sums[-1]+root.val-sum) sums.append(sums[-1]+root.val) ret += path(root.left, sums) + path(root.right, sums) sums.pop() return ret return path(root, [0])<file_sep>class Solution: def removeDuplicates(self, s: str, k: int) -> str: q = [''] x = 1 for c in s: q.append(c) if q[-1] == q[-2]: x += 1 else: x = 1 while x == k: q = q[:-k] x = 1 while x < len(q) and x < k and q[-1] == q[-(x+1)]: x+=1 return ''.join(q[1:])<file_sep>class Solution: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: nums2 = {} for num in nums: if num in nums2: nums2[num] += 1 else: nums2[num] = 1 ans = [[]] for k, v in nums2.items(): ans2 = [] for arr in ans: for i in range(1, v+1): ans2.append(arr + [k] * i) ans.extend(ans2) return ans <file_sep>class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: from collections import defaultdict d = defaultdict(int) for num in nums: d[num] += 1 return [item[0] for item in sorted(d.items(), key=lambda x: x[1], reverse=True)[:k]]<file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode: def depth(node): if not node: return 0 else: return 1 + max(depth(node.left), depth(node.right)) def find_node(node, depth, max_depth): if node: if depth == max_depth: return node else: l = find_node(node.left, depth+1, max_depth) r = find_node(node.right, depth+1, max_depth) if l and r: return node if l: return l if r: return r return None else: return None max_depth = depth(root) node = find_node(root, 1, max_depth) return node <file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def generateTrees(self, n: int) -> List[TreeNode]: def generate(l, r): if l > r: return [None] if l == r: return [TreeNode(l)] trees = [] for i in range(l, r+1): left, right = generate(l, i-1), generate(i+1, r) trees.extend([TreeNode(i, n1, n2) for n1 in left for n2 in right]) return trees return generate(1, n) <file_sep>func insert(intervals [][]int, newInterval []int) [][]int { min := func(a, b int) int { if a < b { return a } return b } max := func(a, b int) int { if a < b { return b } return a } n := len(intervals) res := make([][]int, 0, n+1) for i := 0; i < n; i++ { if newInterval[1] < intervals[i][0] { res = append(res, newInterval) res = append(res, intervals[i:]...) return res } if newInterval[0] > intervals[i][1] { res = append(res, intervals[i]) continue } newInterval[0] = min(newInterval[0], intervals[i][0]) newInterval[1] = max(newInterval[1], intervals[i][1]) } res = append(res, newInterval) return res } <file_sep>class Solution: def removeKdigits(self, num: str, k: int) -> str: q = [] for digit in num: while k > 0 and len(q) > 0 and int(digit) < int(q[-1]): q.pop() k -= 1 q.append(digit) l, r = 0, len(q) - k while l < len(q) and q[l] == "0": l+=1 if l >= r: return "0" return "".join(q[l:r])<file_sep>class Solution: def threeSumClosest(self, nums: List[int], target: int) -> int: n = len(nums) nums.sort() ret = nums[0] + nums[1] + nums[2] for i in range(0, n-2): l, r = i+1, n-1 while l < r: s = nums[i] + nums[l] + nums[r] if abs(target -s) < abs(target-ret): ret = s if s < target: l += 1 elif s > target: r -= 1 else: return target return ret<file_sep>class Solution(object): def findRestaurant(self, list1, list2): """ :type list1: List[str] :type list2: List[str] :rtype: List[str] """ ret, rl, d1, d2 = [], float('inf'), {}, {} for i in range(len(list1)): d1[list1[i]] = i for i in range(len(list2)): d2[list2[i]] = i for r in list1: if r in d2: l = d1[r] + d2[r] if l == rl: ret.append(r) elif l < rl: rl = l ret = [r] return ret <file_sep>class Solution: def missingNumber(self, nums: List[int]) -> int: n = len(nums) x = 0 for i in range(n+1): x ^= i for num in nums: x ^= num return x<file_sep>class Solution(object): def compareVersion(self, version1, version2): """ :type version1: str :type version2: str :rtype: int """ v1 = [int(i) for i in version1.split('.')] v2 = [int(i) for i in version2.split('.')] l1, l2 = len(v1), len(v2) i = 0 ml = max(l1, l2) x,y=0,0 while i < ml: x=v1[i] if i<l1 else 0 y=v2[i] if i<l2 else 0 if x < y: return -1 elif x > y: return 1 i += 1 return 0 <file_sep>class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: n = len(values) vl = [] for i in range(n): vl.append((values[i], labels[i])) vl.sort(reverse=True) ret = 0 lb = {} for i in range(n): if num_wanted <= 0: break v, l = vl[i][0], vl[i][1] lb[l] = lb.get(l, 0) + 1 if lb[l] <= use_limit: num_wanted -= 1 ret += v return ret <file_sep>from heapq import heappush, heappop class Solution: def smallestRangeII(self, A: List[int], K: int) -> int: x, y = min(A), max(A) if x == y: return 0 A = list(set(A)) A.sort() n = len(A) for i in range(n): A[i] = A[i] + K h = [-A[-1]] ret = A[-1] - A[0] x, y = A[0], A[-1] k2 = K * 2 for i in range(n-1, 0, -1): t = A[i] - k2 heappush(h, -t) heappush(h, -A[i-1]) if -h[0]== A[i]: heappop(h) x = min(x, t) y = -h[0] ret = min(ret, abs(y-x)) return ret<file_sep>class Solution: def reverseParentheses(self, s: str) -> str: def reverse(l: list, start: int, end: int): while start < end: l[start], l[end] = l[end], l[start] start += 1 end -= 1 letters = [] bracket_positions = [] for c in s: if c == '(': bracket_positions.append(len(letters)) elif c == ')': reverse(letters, bracket_positions.pop(), len(letters)-1) else: letters.append(c) return ''.join(letters)<file_sep>class Solution: def solveNQueens(self, n: int) -> List[List[str]]: ret = [] m = n * n puzzle = [["." for j in range(n)] for i in range(n)] row = [0] * n col = [0] * n left = [0] * n * 2 right = [0] * n * 2 def dfs(step, q): if q == n: ret.append(["".join(puzzle[i]) for i in range(n)]) return if step == m: return x, y = step // n, step % n z = row[x] + col[y] + left[x+y] + right[n-1-x+y] if z == 0: puzzle[x][y] = "Q" row[x] += 1 col[y] += 1 left[x+y] += 1 right[n-1-x+y] += 1 dfs(step+1, q+1) puzzle[x][y] = "." row[x] -= 1 col[y] -= 1 left[x+y] -= 1 right[n-1-x+y] -= 1 dfs(step+1, q) dfs(0, 0) return ret <file_sep>class Solution { public: int nextGreaterElement(int n) { auto s = to_string(n); if (next_permutation(s.begin(), s.end())) { long x = atol(s.c_str()); if (x > 0x7fffffff) return -1; else return x; } else return -1; } };<file_sep>class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: nums.sort() n = len(nums) ret = [] for j in range(1, n-1): if j > 1 and nums[j] == nums[j-1] and nums[j] == nums[j-2]: continue i, k = 0, n-1 if nums[j] == nums[j-1]: i = j - 1 while i < j and k > j: x = nums[i] + nums[j] + nums[k] if x < 0: i += 1 elif x > 0: k -= 1 else: ret.append([nums[i], nums[j], nums[k]]) i += 1 k -= 1 while i < j and nums[i] == nums[i-1]: i += 1 while k > j and nums[k] == nums[k+1]: k -= 1 return ret<file_sep>class StockSpanner: def __init__(self): self.prices = [] self.k = 1 def next(self, price: int) -> int: self.prices.append(price) if len(self.prices) == 1: self.k = 1 return 1 if price < self.prices[-2]: self.k = 1 return 1 if price == self.prices[-2]: self.k += 1 return self.k if price > self.prices[-2]: self.k += 1 while self.k < len(self.prices) and self.prices[-self.k - 1] <= price: self.k += 1 return self.k # Your StockSpanner object will be instantiated and called as such: # obj = StockSpanner() # param_1 = obj.next(price)<file_sep>func countRangeSum(nums []int, lower int, upper int) int { n := len(nums) if n == 0 { return 0 } sums := make([]int, len(nums)) tmp := make([]int, len(nums)) sums[0] = nums[0] for i := 1; i < n; i++ { sums[i] = sums[i-1] + nums[i] } res := 0 for i := 0; i < n; i++ { if sums[i] >= lower && sums[i] <= upper { res++ } } var merge func(l, r int) merge = func(l, r int) { if r-l <= 1 { return } m := (l + r) / 2 merge(l, m) merge(m, r) i, j, k := l, m, m for ; i < m; i++ { for j < r && sums[j]-sums[i] < lower { j++ } for k < r && sums[k]-sums[i] <= upper { k++ } res += k - j } i, j, k = l, m, 0 for ; i < m && j < r; k++ { if sums[i] < sums[j] { tmp[k] = sums[i] i++ } else { tmp[k] = sums[j] j++ } } for ; i < m; i++ { tmp[k] = sums[i] k++ } for ; j < r; j++ { tmp[k] = sums[j] k++ } for i := 0; i < k; i++ { sums[l+i] = tmp[i] } } merge(0, n) return res }<file_sep>""" # Definition for a Node. class Node: def __init__(self, val, prev, next, child): self.val = val self.prev = prev self.next = next self.child = child """ class Solution: def flatten(self, head: 'Optional[Node]') -> 'Optional[Node]': def flat(node): if not node: return None, None tail = node while True: if tail.child: child, childt = flat(tail.child) if tail.next: childt.next, tail.next.prev = tail.next, childt tail.next, child.prev = child, tail tail.child = None tail = childt if tail.next: tail = tail.next else: break return node, tail h, t = flat(head) return h<file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]: ret = [] q = [(root, str(root.val))] while len(q) > 0: node, path = q.pop() if (not node.left) and (not node.right): ret.append(path) if node.left: q.append((node.left, f'{path}->{node.left.val}')) if node.right: q.append((node.right, f'{path}->{node.right.val}')) return ret <file_sep>class Solution(object): def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ char = [' ', '*', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'] ret = [''] for d in digits: d = int(d) add = [s+c for s in ret for c in char[d]] ret = add if ret[0] == '': return [] else: return ret<file_sep># Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: root = ListNode(0) root.next = head node = root while node and node.next and node.next.next: val = node.next.val node2 = node.next if node2.next.val != val: node = node.next continue while node2 and node2.val == val: node2 = node2.next node.next = node2 return root.next<file_sep>class Solution(object): def containsNearbyAlmostDuplicate(self, nums, k, t): """ :type nums: List[int] :type k: int :type t: int :rtype: bool """ n = len(nums) sum = [0] *(n + 1) def lowbit(x): return x & -x def update(x, v): while x <= n: sum[x] += v x += lowbit(x) def query(x): x=min(x, n) s = 0 while x>0: s += sum[x] x -= lowbit(x) return s nums = [(nums[i], i+1) for i in range(n)] nums.sort() #print(nums) y = 0 for x in range(n): update(nums[x][1], -1) while y < n and nums[y][0] - nums[x][0] <= t: update(nums[y][1], 1) y += 1 if query(nums[x][1]+k) - query(nums[x][1]-k-1) > 0: return True return False <file_sep>class Solution(object): def myAtoi(self, str): """ :type str: str :rtype: int """ n = len(str) i = 0 ret = 0 flag = 0 while i < n and str[i].isspace(): i += 1 if i < n and str[i] == '-': i +=1 flag = 1 elif i < n and str[i] == '+': i += 1 flag = 2 if i < n and str[i].isdigit(): while i < n and str[i].isdigit(): ret = ret * 10 + int(str[i]) i += 1 if flag == 1: ret = -ret if ret > 2147483647: ret = 2147483647 elif ret < -2147483648: ret = -2147483648 return ret <file_sep>class Solution: def shiftingLetters(self, S, shifts): """ :type S: str :type shifts: List[int] :rtype: str """ def shift(c, x): return chr(((ord(c) - ord('a') + x) % 26) + ord('a')) s = list(S) n = len(shifts) for i in range(n-2, -1, -1): shifts[i] += shifts[i + 1] for i in range(n): s[i] = shift(s[i],shifts[i]) return ''.join(s) <file_sep>func singleNumber(nums []int) []int { res := make([]int, 2) x := 0 for _, v := range nums { x ^= v } x = x & (-x) for _, v := range nums { if v&x == 0 { res[0] ^= v } else { res[1] ^= v } } return res } <file_sep>class Solution(object): def sequentialDigits(self, low, high): """ :type low: int :type high: int :rtype: List[int] """ ret = [] s = '123456789' lena, lenb = len(str(low)), len(str(high)) for i in range(lena, lenb+1): for j in range(0, 10-i): x = int(s[j:j+i]) if low <= x and x <= high: ret.append(x) elif x > high: break return ret<file_sep>class Solution: def partitionDisjoint(self, A: List[int]) -> int: n = len(A) inf = float('inf') minx = [inf for i in range(n+1)] for i in range(n-1, -1, -1): minx[i] = min(A[i], minx[i+1]) maxx = -inf for i in range(n): maxx = max(A[i], maxx) if maxx <= minx[i+1]: return i+1 return n<file_sep>class Solution: def maxProfit(self, prices: List[int]) -> int: ret = 0 p = prices[0] for price in prices: if price > p: ret += price - p p = price return ret<file_sep>class Solution(object): def convertToBase7(self, num): """ :type num: int :rtype: str """ if num ==0 : return '0' ret = '' sign = '' if num < 0: sign = '-' num = - num while num: ret = str(num%7) + ret num /= 7 return sign + ret <file_sep>""" # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def preorder(self, root: 'Node') -> List[int]: res = [] q = [] if root: q = [root] while len(q) > 0: node = q.pop() res.append(node.val) if node.children: q.extend(list(node.children)[::-1]) return res <file_sep>func increasingTriplet(nums []int) bool { n := len(nums) if n < 3 { return false } maxP := 0 for i := 0; i < n; i++ { j := maxP for j >= 0 && nums[i] <= nums[j] { j-- } nums[j+1] = nums[i] if j+1 > maxP { maxP = j + 1 if maxP == 2 { return true } } } return false } <file_sep>class Solution: def permute(self, nums: List[int]) -> List[List[int]]: permutations = [] n = len(nums) def permutation(start): if start == n: permutations.append(nums[:]) return for i in range(start, n): nums[i], nums[start] = nums[start], nums[i] permutation(start+1) nums[i], nums[start] = nums[start], nums[i] permutation(0) return permutations<file_sep>class Solution: def findMaxLength(self, nums: List[int]) -> int: ans = 0 min_nums = {0: -1} n = len(nums) if nums[0] == 0: nums[0] = -1 min_nums[-1] = 0 else: min_nums[1] = 0 for i in range(1, n): num = nums[i] if num == 0: num = -1 nums[i] = num + nums[i-1] if nums[i] in min_nums: ans = max(ans, i-min_nums[nums[i]]) else: min_nums[nums[i]] = i return ans<file_sep>class RLEIterator: def __init__(self, encoding: List[int]): self.encoding = encoding self.i = 0 self.l = len(self.encoding) self.val = 0 self.t = 0 def next(self, n: int) -> int: val = -1 while n > 0: if self.t > 0: x = min(n, self.t) n -= x self.t -= x val = self.val else: if self.i + 1 >= self.l: return -1 self.t = self.encoding[self.i] self.val = self.encoding[self.i + 1] self.i = self.i + 2 return val # Your RLEIterator object will be instantiated and called as such: # obj = RLEIterator(encoding) # param_1 = obj.next(n)<file_sep>class Solution: def countPrimes(self, n: int) -> int: if n <= 1: return 0 nums = [1] * n nums[0] = nums[1] = 0 for i in range(n): if nums[i] == 0: continue x = i + i while x < n: nums[x] = 0 x += i return sum(nums) <file_sep>class Solution: def checkValidString(self, s): """ :type s: str :rtype: bool """ n = len(s) dp = [True] dp[0] = True dp2 = [] for i, c in enumerate(s, 1): if c == '(': dp2 = [False] + dp elif c == ')': dp2 = dp[1:] + [False, False] else: x = [False] + dp y = dp[1:] + [False, False] z = dp + [False] dp2 = [x[i] or y[i] or z[i] for i in range(i+1)] dp = dp2 return dp[0] <file_sep>class Solution: def getRow(self, rowIndex: int) -> List[int]: row = [1] for i in range(1, rowIndex+1): row2 = [1] *(i + 1) for j in range(i-1): row2[j+1] = row[j] + row[j+1] row = row2 return row
86cd22354f2431087c9b3ff06188f071afb3eb72
[ "Ruby", "Python", "C", "Go", "C++" ]
484
Python
tlxxzj/leetcode
06dbf4f5b505a6a41e0d93367eedd231b611a84b
0c072a74d7e61ef4700388122f2270e46c4ac22e
refs/heads/main
<file_sep># Basic-C-Calculator Its a basic Console Calculator , that can +, -, / and * Note: Made that programm just for fun. <file_sep>#include <stdio.h> #include <stdbool.h> #include <time.h> int main(void) { bool loop = true; double num1; double num2; char op; char y_or_n; printf("\nThats a basic calculator!\n\n"); //time time_t t; struct tm * ts; //Time now t = time(NULL); ts = localtime(&t); printf("It is: %s\n", asctime(ts)); //loop while(loop){ //Input num 1 printf("\n\nEnter a number: \n"); scanf("%lf", &num1); //Input operator printf("\nEnter a operator: "); scanf(" %c", &op); //Input num 2 printf("\nEnter another number: "); scanf("%lf", &num2); //Calculation if(op == '+'){ printf("\nYour result is: %f\n", num1 + num2); } else if(op == '-'){ printf("\nYour result is: %f\n", num1 - num2); } else if(op == '/'){ printf("\nYour result is: %f\n", num1 / num2); } else if(op == '*'){ printf("\nYour result is: %f\n", num1 * num2); } //If end or not printf("\nAgain? (Y/N): "); scanf(" %c", &y_or_n); if(y_or_n == 'N' || y_or_n == 'n'){ printf("\nOK, bye!\n"); loop = false; } else if(y_or_n == 'Y' || y_or_n == 'y'){ loop = true; } } return 0; }
100634291137b8e22382ea4951cb31643edc5ce0
[ "Markdown", "C" ]
2
Markdown
Tasy-real/Basic-C-Calculator
a7a3b959764ed2e4c70e9b1d1e2ccaf965764fe6
7e29ee8dfb73e51a98c5eef17785661c081d5f98
refs/heads/master
<file_sep>from PIL import Image import pytesseract import os if os.path.exists("output.txt"): os.remove("output.txt") # Simple image to string output = pytesseract.image_to_string(Image.open('image.png')) print(output) f = open("output.txt", "w+") f.write(output) f.close()
8dce5aee884ebdd8160dee637ccd34bac1c51980
[ "Python" ]
1
Python
leandrommoliveira/image-recognition
65a4bf96d887b08e58969c2d5c22c6a1f81f8a41
67fe1d2b98da36e5331b6ddb357f675100a781de
refs/heads/master
<repo_name>automaticinfotech/ECOMM<file_sep>/src/main/java/com/aits/FactoryClasses/IRandomNumber.java package com.aits.FactoryClasses; public interface IRandomNumber { public int genrateRandomNumber(); } <file_sep>/src/main/java/com/aits/model/DiscountMaster.java package com.aits.model; import java.util.List; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.ObjectIdGenerators; @Entity @Table(name = "Discount_Master") @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class,property="discountMasterId",scope = DiscountMaster.class) public class DiscountMaster { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "Discount_Id") private int discountMasterId; @Column(name = "Discount_Name", length = 50) private String dicountMasterName; // Bidirectional relationship with SubProductMasterDiscountMapper @JsonBackReference @OneToMany(targetEntity = SubProductMasterDiscountMapper.class, cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE }, mappedBy = "discountMaster") private Set<SubProductMasterDiscountMapper> subProductMasterDiscountMapperSet; @Transient private List<DiscountMaster> discountMasterList; public int getDiscountMasterId() { return discountMasterId; } public void setDiscountMasterId(int discountMasterId) { this.discountMasterId = discountMasterId; } public String getDicountMasterName() { return dicountMasterName; } public void setDicountMasterName(String dicountMasterName) { this.dicountMasterName = dicountMasterName; } public Set<SubProductMasterDiscountMapper> getSubProductMasterDiscountMapperSet() { return subProductMasterDiscountMapperSet; } public void setSubProductMasterDiscountMapperSet( Set<SubProductMasterDiscountMapper> subProductMasterDiscountMapperSet) { this.subProductMasterDiscountMapperSet = subProductMasterDiscountMapperSet; } public List<DiscountMaster> getDiscountMasterList() { return discountMasterList; } public void setDiscountMasterList(List<DiscountMaster> discountMasterList) { this.discountMasterList = discountMasterList; } } <file_sep>/src/main/java/com/aits/model/CartDetails.java package com.aits.model; import java.util.List; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Transient; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.ObjectIdGenerators; @Entity @Table(name = "CartDetails") @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property = "cartDetailsId", scope = CartDetails.class) public class CartDetails { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "CartDetails_Id") private int cartDetailsId; @Column(name = "Quantity", length = 2) private int quantity; @Column(name = "Is_Active", length = 2) private String isActive; @ManyToOne(targetEntity = EndUserDetails.class, cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE }) @JoinColumn(name = "Fk_EndUserId") private EndUserDetails endUserDetails; /* * This is one to many relationship but instead of making new table I * created it through one to one only and removed unique constraint in join * coloumn */ @OneToOne(targetEntity = SubProductMaster.class, cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE }) @JoinColumn(name = "Fk_SubProductId") private SubProductMaster subProductMaster; @Transient private List<CartDetails> cartDetailList; public int getCartDetailsId() { return cartDetailsId; } public void setCartDetailsId(int cartDetailsId) { this.cartDetailsId = cartDetailsId; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public String getIsActive() { return isActive; } public void setIsActive(String isActive) { this.isActive = isActive; } public EndUserDetails getEndUserDetails() { return endUserDetails; } public void setEndUserDetails(EndUserDetails endUserDetails) { this.endUserDetails = endUserDetails; } public SubProductMaster getSubProductMaster() { return subProductMaster; } public void setSubProductMaster(SubProductMaster subProductMaster) { this.subProductMaster = subProductMaster; } public List<CartDetails> getCartDetailList() { return cartDetailList; } public void setCartDetailList(List<CartDetails> cartDetailList) { this.cartDetailList = cartDetailList; } } <file_sep>/src/main/java/com/aits/constant/AppConstant.java package com.aits.constant; public interface AppConstant { String ADMIN_LOGIN_AUTHENTICATION = "/adminLoginAuthentication"; String ADMIN_SIGN_OUT = "/adminSignOut"; String USER_LOGIN = "/userLogin"; String URI = "http://localhost:8080/ECOMM-WS/"; String ROOT = "/"; String HOME = "/home"; String HELLO = "/Hello"; String LIST_PRODUCT = "/listProduct"; String GET_PRODUCT_BY_ID = "/getProductById"; /*Product Mgmt*/ String GET_CATEGORY_MASTER_LIST = "/getCategoryMasterList"; String INSERT_CATEGORY_MASTER = "/insertCategoryMaster"; String GET_CATEGORY_MASTER_INFORMATION_BY_ID = "/getCategoryMasterInformationById/{categoryMasterId}"; String GET_CATEGORY_MASTER_INFORMATION_BY_CATEGORY_ID = "/getCategoryMasterInformationById/"; String UPDATE_CATEGORY_MASTER = "/updateCategoryMaster"; String UPDATE_CATEGORY_STATUS = "/updateCategoryStatus"; /* added by santosh 12/04/2017 */ String AdminStates="/adminStates"; String SAVE_STATE="/saveState"; String ADMIN_UPDATE_STATE_STATUS="/updateStateStatus"; String ADMIN_EDIT_STATE="/editState"; String SAVE_CITY="/saveCity"; String ADMIN_EDIT_CITY="/editCity"; String ADMIN_CITYS="adminAllCitys"; String ADMIN_UPDATE_CITY_STATUS="/updateCityStatus"; /*Discount Mgmt*/ String GET_DISCOUNT_LIST="/getDiscountMasterList"; String ADD_DISCOUNT="/addDiscountMasterInformation"; String UPDATE_DISCOUNT="/updateDiscountMasterInformation"; String GET_DISCOUNT_INFO_BY_ID="/getDiscountMasterInformationById/"; String GET_DISCOUNT_MAPPER_LIST="/getSubProductDiscountMapperList"; String GET_SUB_PRODUCT_LIST="/getSubProductMasterList"; String ADD_DISCOUNT_MAPPER_INFO="/insertSubProductDiscountMapperInformation"; //user registration String USER_REGISTRATION="/registration"; String USER_PARTIALREGISTRATION="/partialRegistration"; String USER_CENTRALREGISTRATION="/centralRegistration"; String USER_FINALREGISTRATION="/finalRegistration"; } <file_sep>/src/main/java/com/aits/controller/AdminSubProductDiscountMapperController.java package com.aits.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.client.RestTemplate; import com.aits.constant.AppConstant; import com.aits.dto.DiscountMasterDto; import com.aits.dto.SubProductMasterDiscountMapperDto; import com.aits.dto.SubProductMasterDto; import com.fasterxml.jackson.databind.ObjectMapper; @Controller public class AdminSubProductDiscountMapperController implements AppConstant { @RequestMapping(value=GET_DISCOUNT_MAPPER_LIST, method = RequestMethod.GET) public String getDiscount(Model model)throws Exception { model.addAttribute("subProductMasterDiscountMapperDto",new SubProductMasterDiscountMapperDto()); RestTemplate restTemplate=new RestTemplate(); String discountMapperListResponse=restTemplate.getForObject(URI+GET_DISCOUNT_MAPPER_LIST, String.class); SubProductMasterDiscountMapperDto subProductMasterDiscountMapperDto=new ObjectMapper().readValue(discountMapperListResponse, SubProductMasterDiscountMapperDto.class); String discountListResponse=restTemplate.getForObject(URI+GET_DISCOUNT_LIST, String.class); DiscountMasterDto discountMasterDto=new ObjectMapper().readValue(discountListResponse, DiscountMasterDto.class); String subProductListResponse=restTemplate.getForObject(URI+GET_SUB_PRODUCT_LIST, String.class); SubProductMasterDto subProductMasterDto=new ObjectMapper().readValue(subProductListResponse, SubProductMasterDto.class); model.addAttribute("subProductMasterList",subProductMasterDto.getSubProductMasterList()); model.addAttribute("discountMasterList",discountMasterDto.getDiscountMasterList()); model.addAttribute("subProductMasterDiscountMapperList",subProductMasterDiscountMapperDto.getSubProductMasterDiscountMapperList()); return "admin/mapDiscount"; } @RequestMapping(value=ADD_DISCOUNT_MAPPER_INFO,method=RequestMethod.POST) public String addDiscount(@ModelAttribute("subProductMasterDiscountMapperDto") SubProductMasterDiscountMapperDto subProductMasterDiscountMapperDto,Model model){ System.out.println("Inside Add Discount Mappper Information"); System.out.println("From Date"+subProductMasterDiscountMapperDto.getSubProductMasterDiscountMapperFromDate()); System.out.println("To Date"+subProductMasterDiscountMapperDto.getSubProductMasterDiscountMapperToDate()); System.out.println("SubProduct Name="+subProductMasterDiscountMapperDto.getSubProductMaster().getSubProductName()); System.out.println("Discount Name="+subProductMasterDiscountMapperDto.getDiscountMaster().getDicountMasterName()); return "admin/mapDiscount"; } } <file_sep>/src/main/java/com/aits/model/UserMaster.java package com.aits.model; import java.util.List; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.ObjectIdGenerators; @Entity @Table(name = "User_Master") @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="userMasterId",scope = UserMaster.class) public class UserMaster { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "User_Master_Id") private int userMasterId; @Column(name = "User_Type", length = 25) private String userType; @OneToMany(targetEntity = EndUserDetails.class, cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE }, mappedBy = "userMaster") private Set<EndUserDetails> endUserDetailSet; @Transient private List<UserMaster> userMasterList; public int getUserMasterId() { return userMasterId; } public void setUserMasterId(int userMasterId) { this.userMasterId = userMasterId; } public String getUserType() { return userType; } public void setUserType(String userType) { this.userType = userType; } public Set<EndUserDetails> getEndUserDetailSet() { return endUserDetailSet; } public void setEndUserDetailSet(Set<EndUserDetails> endUserDetailSet) { this.endUserDetailSet = endUserDetailSet; } public List<UserMaster> getUserMasterList() { return userMasterList; } public void setUserMasterList(List<UserMaster> userMasterList) { this.userMasterList = userMasterList; } } <file_sep>/src/main/java/com/aits/model/SubProductMaster.java package com.aits.model; import java.util.List; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Transient; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.ObjectIdGenerators; @Entity @Table(name = "SubProduct_Master") @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class,property="subProductId",scope = SubProductMaster.class) public class SubProductMaster { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "Sub_Product_Id") private int subProductId; @Column(name = "Sub_Product_Name", length = 50) private String subProductName; @Column(name = "Sub_Product_Color", length = 20) private String subProductColor; @Column(name = "Sub_Product_Weight", length = 10) private double subProductWeigth; @Column(name = "Sub_Product_Quantity", length = 10) private int subProductQuantity; @Column(name = "Sub_Product_Price", length = 50) private double subProductPrice; @Column(name = "Is_Active", length = 2) private String isActive; @ManyToOne(targetEntity = ProductMaster.class, cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE } ) @JoinColumn(name = "Fk_ProductMasterId") private ProductMaster productMaster; // Bidirectional Relationship @OneToMany(targetEntity = ImageMaster.class, cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE }, mappedBy = "subProductMaster") private Set<ImageMaster> imageMasterSet; // Bidirectional Relationship with SubProductMasterDiscountMapper @OneToMany(targetEntity = SubProductMasterDiscountMapper.class, cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE }, mappedBy = "subProductMaster") private Set<SubProductMasterDiscountMapper> subProductMasterDiscountMapperSet; // Bidirectional Relationship with CartDetails @OneToOne(targetEntity = CartDetails.class, cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE }, mappedBy = "subProductMaster") private CartDetails cartDetails; // Bidirectional Relationship with CartDetails @OneToOne(targetEntity = WishListManagement.class, cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE }, mappedBy = "subProductMaster") private WishListManagement wishListManagement; @Transient private List<SubProductMaster> subProductMasterList; public int getSubProductId() { return subProductId; } public void setSubProductId(int subProductId) { this.subProductId = subProductId; } public String getSubProductName() { return subProductName; } public void setSubProductName(String subProductName) { this.subProductName = subProductName; } public String getSubProductColor() { return subProductColor; } public void setSubProductColor(String subProductColor) { this.subProductColor = subProductColor; } public double getSubProductWeigth() { return subProductWeigth; } public void setSubProductWeigth(double subProductWeigth) { this.subProductWeigth = subProductWeigth; } public int getSubProductQuantity() { return subProductQuantity; } public void setSubProductQuantity(int subProductQuantity) { this.subProductQuantity = subProductQuantity; } public double getSubProductPrice() { return subProductPrice; } public void setSubProductPrice(double subProductPrice) { this.subProductPrice = subProductPrice; } public String getIsActive() { return isActive; } public void setIsActive(String isActive) { this.isActive = isActive; } public ProductMaster getProductMaster() { return productMaster; } public void setProductMaster(ProductMaster productMaster) { this.productMaster = productMaster; } public Set<ImageMaster> getImageMasterSet() { return imageMasterSet; } public void setImageMasterSet(Set<ImageMaster> imageMasterSet) { this.imageMasterSet = imageMasterSet; } public Set<SubProductMasterDiscountMapper> getSubProductMasterDiscountMapperSet() { return subProductMasterDiscountMapperSet; } public void setSubProductMasterDiscountMapperSet( Set<SubProductMasterDiscountMapper> subProductMasterDiscountMapperSet) { this.subProductMasterDiscountMapperSet = subProductMasterDiscountMapperSet; } public CartDetails getCartDetails() { return cartDetails; } public void setCartDetails(CartDetails cartDetails) { this.cartDetails = cartDetails; } public WishListManagement getWishListManagement() { return wishListManagement; } public void setWishListManagement(WishListManagement wishListManagement) { this.wishListManagement = wishListManagement; } public List<SubProductMaster> getSubProductMasterList() { return subProductMasterList; } public void setSubProductMasterList(List<SubProductMaster> subProductMasterList) { this.subProductMasterList = subProductMasterList; } } <file_sep>/src/main/java/com/aits/controller/AuthenticationInterceptor.java package com.aits.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import com.aits.dto.EndUserDetailsDto; @Component public class AuthenticationInterceptor extends HandlerInterceptorAdapter { /*@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String uri = request.getRequestURI(); if(uri.endsWith("getCategoryMasterList") || uri.endsWith("adminDashboard")) { EndUserDetailsDto userData = (EndUserDetailsDto) request.getSession().getAttribute("LOGGEDIN_USER"); if(userData == null) { response.sendRedirect("adminLogin"); return false; } } return true; }*/ }<file_sep>/src/main/java/com/aits/controller/AddressManagementController.java package com.aits.controller; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.client.RestTemplate; import com.aits.constant.AppConstant; import com.aits.dto.AddressMasterDto; import com.aits.dto.CityMasterDto; import com.aits.dto.PincodeMasterDto; import com.aits.dto.StateMasterDto; import com.aits.model.StateMaster; import com.fasterxml.jackson.databind.ObjectMapper; @Controller public class AddressManagementController implements AppConstant { @RequestMapping(value="/adminDashboard", method = RequestMethod.GET) public String adminDashboard() { return "admin/adminDashboard"; } /*****************************State Operations****************************************/ @RequestMapping(value=AdminStates, method = RequestMethod.GET) public String addState(Model model)throws Exception { model.addAttribute("stateMasterDto",new StateMasterDto()); RestTemplate restTemplate=new RestTemplate(); String stateListResponce=restTemplate.postForObject(URI+AdminStates,StateMasterDto.class, String.class); StateMasterDto stateList=new ObjectMapper().readValue(stateListResponce, StateMasterDto.class); model.addAttribute("stateList",stateList.getStateMasterList()); model.addAttribute("operation","Add State"); return "admin/addState"; } @RequestMapping(value=SAVE_STATE, method = RequestMethod.POST) public String saveState(@ModelAttribute("stateMasterDto")StateMasterDto stateMasterDto ,Model model)throws Exception { RestTemplate restTemplate = new RestTemplate(); String stateMasterDtoResponce=restTemplate.postForObject(URI+SAVE_STATE,stateMasterDto,String.class); StateMasterDto stDto=new ObjectMapper().readValue(stateMasterDtoResponce,StateMasterDto.class); model.addAttribute("stateList",stDto.getStateMasterList()); model.addAttribute("stateMasterDto",stateMasterDto); model.addAttribute("operation","Add State"); model.addAttribute("msg","State Save Successfull!!"); return "admin/addState"; } @RequestMapping(value=ADMIN_EDIT_STATE, method = RequestMethod.GET) public String editState(@RequestParam("stateId")int stateId,Model model)throws Exception { RestTemplate restTemplate = new RestTemplate(); StateMasterDto dto=new StateMasterDto(); dto.setStateId(stateId); String stateMasterDtoResponce=restTemplate.postForObject(URI+ADMIN_EDIT_STATE,dto,String.class); StateMasterDto stDto=new ObjectMapper().readValue(stateMasterDtoResponce,StateMasterDto.class); model.addAttribute("stateList",stDto.getStateMasterList()); model.addAttribute("operation","Update State"); model.addAttribute("stateMasterDto",stDto); return "admin/addState"; } @RequestMapping(value=ADMIN_UPDATE_STATE_STATUS,method=RequestMethod.POST) public @ResponseBody String updateStateStatus(@RequestBody StateMasterDto stateMasterDto,Model model)throws Exception{ RestTemplate restTemplate=new RestTemplate(); String stateListResponce=restTemplate.postForObject(URI+ADMIN_UPDATE_STATE_STATUS,stateMasterDto, String.class); StateMasterDto stateList=new ObjectMapper().readValue(stateListResponce, StateMasterDto.class); return"admin/addState"; } /*****************************city Operations****************************************/ @RequestMapping(value="/adminAddCity", method = RequestMethod.GET) public String addcity(Model model) throws Exception{ RestTemplate restTemplate=new RestTemplate(); String stateListResponce=restTemplate.postForObject(URI+AdminStates,StateMasterDto.class, String.class); StateMasterDto stateList=new ObjectMapper().readValue(stateListResponce, StateMasterDto.class); model.addAttribute("stateList",stateList.getStateMasterList()); String cityListResponce=restTemplate.postForObject(URI+ADMIN_CITYS,CityMasterDto.class, String.class); CityMasterDto cityListDto=new ObjectMapper().readValue(cityListResponce, CityMasterDto.class); model.addAttribute("cityList",cityListDto.getCityMasterList()); model.addAttribute("cityMasterDto",new CityMasterDto()); return "admin/addCity"; } @RequestMapping(value=SAVE_CITY, method = RequestMethod.POST) public String saveCity(@ModelAttribute("cityMasterDto")CityMasterDto cityMasterDto,Model model)throws Exception { RestTemplate restTemplate = new RestTemplate(); restTemplate.postForObject(URI+SAVE_CITY,cityMasterDto,String.class); String stateListResponce=restTemplate.postForObject(URI+AdminStates,StateMasterDto.class, String.class); StateMasterDto stateListDto=new ObjectMapper().readValue(stateListResponce, StateMasterDto.class); model.addAttribute("stateList",stateListDto.getStateMasterList()); String cityListResponce=restTemplate.postForObject(URI+ADMIN_CITYS,CityMasterDto.class, String.class); CityMasterDto cityListDto=new ObjectMapper().readValue(cityListResponce, CityMasterDto.class); model.addAttribute("cityList",cityListDto.getCityMasterList()); model.addAttribute("cityMasterDto",new CityMasterDto()); model.addAttribute("msg","City Save Successfull!!"); return "admin/addCity"; } @RequestMapping(value=ADMIN_EDIT_CITY, method = RequestMethod.GET) public String editCity(@RequestParam("cityId")int cityId,Model model)throws Exception { RestTemplate restTemplate = new RestTemplate(); CityMasterDto dto=new CityMasterDto(); dto.setCityId(cityId); String cityMasterDtoResponce=restTemplate.postForObject(URI+ADMIN_EDIT_CITY,dto,String.class); CityMasterDto ctDto=new ObjectMapper().readValue(cityMasterDtoResponce,CityMasterDto.class); model.addAttribute("cityMasterDto",ctDto); String stateListResponce=restTemplate.postForObject(URI+AdminStates,StateMasterDto.class, String.class); StateMasterDto stateListDto=new ObjectMapper().readValue(stateListResponce, StateMasterDto.class); model.addAttribute("stateList",stateListDto.getStateMasterList()); String cityListResponce=restTemplate.postForObject(URI+ADMIN_CITYS,CityMasterDto.class, String.class); CityMasterDto cityListDto=new ObjectMapper().readValue(cityListResponce, CityMasterDto.class); model.addAttribute("cityList",cityListDto.getCityMasterList()); model.addAttribute("operation","Update City"); return "admin/addCity"; } @RequestMapping(value=ADMIN_UPDATE_CITY_STATUS,method=RequestMethod.POST) public @ResponseBody String updateCityStatus(@RequestBody CityMasterDto cityMasterDto,Model model)throws Exception{ RestTemplate restTemplate=new RestTemplate(); String stateListResponce=restTemplate.postForObject(URI+ADMIN_UPDATE_CITY_STATUS,cityMasterDto, String.class); return"admin/addCity"; } @RequestMapping(value="/adminAddPincode", method = RequestMethod.GET) public String addPincode(Model model) { model.addAttribute("pincodeMasterDto",new PincodeMasterDto()); return "admin/addPincode"; } @RequestMapping(value="/adminAddAddress", method = RequestMethod.GET) public String addAddressLine(Model model) { model.addAttribute("addressMasterDto",new AddressMasterDto()); return "admin/addAddress"; } } <file_sep>/src/main/java/com/aits/model/AddressMaster.java package com.aits.model; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Transient; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.ObjectIdGenerators; @Entity @Table(name = "Address_Master") @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property = "addressId", scope = AddressMaster.class) public class AddressMaster { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "Address_Id") private int addressId; @Column(name = "Address_Line_1", length = 100) private String addressLine1; @Column(name = "Address_Line_2", length = 100) private String addressLine2; @OneToOne(targetEntity = PincodeMaster.class, cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE }) @JoinColumn(name = "Fk_PincodeId") private PincodeMaster pincodeMaster; @JsonBackReference @OneToOne(targetEntity = EndUserDetails.class, cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE }, mappedBy = "addressMaster") private EndUserDetails endUserDetails; @Transient private List<AddressMaster> addressMasterList; @Column(name = "Is_Active", length = 2) private String isActive; public String getIsActive() { return isActive; } public void setIsActive(String isActive) { this.isActive = isActive; } public int getAddressId() { return addressId; } public void setAddressId(int addressId) { this.addressId = addressId; } public String getAddressLine1() { return addressLine1; } public void setAddressLine1(String addressLine1) { this.addressLine1 = addressLine1; } public String getAddressLine2() { return addressLine2; } public void setAddressLine2(String addressLine2) { this.addressLine2 = addressLine2; } public PincodeMaster getPincodeMaster() { return pincodeMaster; } public void setPincodeMaster(PincodeMaster pincodeMaster) { this.pincodeMaster = pincodeMaster; } public EndUserDetails getEndUserDetails() { return endUserDetails; } public void setEndUserDetails(EndUserDetails endUserDetails) { this.endUserDetails = endUserDetails; } public List<AddressMaster> getAddressMasterList() { return addressMasterList; } public void setAddressMasterList(List<AddressMaster> addressMasterList) { this.addressMasterList = addressMasterList; } } <file_sep>/src/main/java/com/aits/model/EndUserDetails.java package com.aits.model; import java.util.Date; import java.util.List; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Transient; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.JsonManagedReference; import com.fasterxml.jackson.annotation.ObjectIdGenerators; @Entity @Table(name = "EndUser_Details") @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property = "endUserId", scope = EndUserDetails.class) public class EndUserDetails { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "User_Id") private int endUserId; @Column(name = "First_Name", length = 32) private String userFirstName; @Column(name = "Last_Name", length = 32) private String userLastName; @Column(name = "Gender", length = 3) private String userGender; @Column(name = "Mobile_Number", length = 10) private Long userMobileNumber; @Column(name = "Email_Id", length = 70) private String userEmailId; @Column(name = "Date_Of_Birth", length = 70) private Date userDateOfBirth; @Column(name = "Age", length = 3) private int userAge; @Column(name = "User_Password", length = 30) private String userPassword; @Column(name = "OneTime_Password", length = 30) private int OneTimePassword; @Column(name = "Is_Active", length = 2) private String isActive; @JsonManagedReference @OneToOne(targetEntity = AddressMaster.class, cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE }, fetch = FetchType.EAGER) @JoinColumn(name = "Fk_addressId", unique = true) private AddressMaster addressMaster; // bidirectional RelationShip @ManyToOne(targetEntity = UserMaster.class, cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE }) @JoinColumn(name = "Fk_User_MasterId") private UserMaster userMaster; // Bidirectional Relationship with CartDetails @OneToMany(targetEntity = CartDetails.class, cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE }, mappedBy = "endUserDetails") private Set<CartDetails> cartDetailSet; // Bidirectional Relationship with WishListManagement @OneToMany(targetEntity = WishListManagement.class, cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE }, mappedBy = "endUserDetails") private Set<WishListManagement> wishListManagementSet; @Transient private List<EndUserDetails> endUserDetailList; public int getEndUserId() { return endUserId; } public void setEndUserId(int endUserId) { this.endUserId = endUserId; } public String getUserFirstName() { return userFirstName; } public void setUserFirstName(String userFirstName) { this.userFirstName = userFirstName; } public String getUserLastName() { return userLastName; } public void setUserLastName(String userLastName) { this.userLastName = userLastName; } public String getUserGender() { return userGender; } public void setUserGender(String userGender) { this.userGender = userGender; } public Long getUserMobileNumber() { return userMobileNumber; } public void setUserMobileNumber(Long userMobileNumber) { this.userMobileNumber = userMobileNumber; } public String getUserEmailId() { return userEmailId; } public void setUserEmailId(String userEmailId) { this.userEmailId = userEmailId; } public Date getUserDateOfBirth() { return userDateOfBirth; } public void setUserDateOfBirth(Date userDateOfBirth) { this.userDateOfBirth = userDateOfBirth; } public int getUserAge() { return userAge; } public void setUserAge(int userAge) { this.userAge = userAge; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = <PASSWORD>; } public int getOneTimePassword() { return OneTimePassword; } public void setOneTimePassword(int oneTimePassword) { OneTimePassword = oneTimePassword; } public String getIsActive() { return isActive; } public void setIsActive(String isActive) { this.isActive = isActive; } public AddressMaster getAddressMaster() { return addressMaster; } public void setAddressMaster(AddressMaster addressMaster) { this.addressMaster = addressMaster; } public UserMaster getUserMaster() { return userMaster; } public void setUserMaster(UserMaster userMaster) { this.userMaster = userMaster; } public Set<CartDetails> getCartDetailSet() { return cartDetailSet; } public void setCartDetailSet(Set<CartDetails> cartDetailSet) { this.cartDetailSet = cartDetailSet; } public Set<WishListManagement> getWishListManagementSet() { return wishListManagementSet; } public void setWishListManagementSet(Set<WishListManagement> wishListManagementSet) { this.wishListManagementSet = wishListManagementSet; } public List<EndUserDetails> getEndUserDetailList() { return endUserDetailList; } public void setEndUserDetailList(List<EndUserDetails> endUserDetailList) { this.endUserDetailList = endUserDetailList; } } <file_sep>/src/main/java/com/aits/controller/AdminProductMgmtController.java package com.aits.controller; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.client.RestTemplate; import com.aits.constant.AppConstant; import com.aits.dto.CategoryMasterDto; import com.fasterxml.jackson.databind.ObjectMapper; @Controller public class AdminProductMgmtController implements AppConstant{ @RequestMapping(value=GET_CATEGORY_MASTER_LIST, method = RequestMethod.GET) public String getCategoryMasterList(ModelMap model,HttpServletRequest request) throws IOException { RestTemplate restTemplate = new RestTemplate(); String categoryMasterDtoResponse = restTemplate.getForObject(URI+GET_CATEGORY_MASTER_LIST, String.class); ObjectMapper mapper = new ObjectMapper(); CategoryMasterDto dto = mapper.readValue(categoryMasterDtoResponse, CategoryMasterDto.class); model.addAttribute("categoryMasterDtoResponse",dto); return "admin/addCategory"; } @RequestMapping(value=INSERT_CATEGORY_MASTER, method = RequestMethod.POST) public String insertCategoryMaster(@ModelAttribute("categoryMasterDto") CategoryMasterDto categoryMasterDto, ModelMap model,HttpServletRequest request) throws IOException { RestTemplate restTemplate = new RestTemplate(); String categoryMasterDtoResponse = restTemplate.postForObject(URI+INSERT_CATEGORY_MASTER, categoryMasterDto,String.class); ObjectMapper mapper = new ObjectMapper(); CategoryMasterDto dto = mapper.readValue(categoryMasterDtoResponse, CategoryMasterDto.class); model.addAttribute("categoryMasterDtoResponse",dto); return "admin/addCategory"; } @RequestMapping(value=GET_CATEGORY_MASTER_INFORMATION_BY_ID, method = RequestMethod.GET) public String getCategoryMasterInformationById(@PathVariable("categoryMasterId") int categoryMasterId, ModelMap model,HttpServletRequest request) throws IOException { RestTemplate restTemplate = new RestTemplate(); String categoryMasterDtoResponse = restTemplate.getForObject(URI+GET_CATEGORY_MASTER_INFORMATION_BY_CATEGORY_ID+categoryMasterId,String.class); ObjectMapper mapper = new ObjectMapper(); CategoryMasterDto dto = mapper.readValue(categoryMasterDtoResponse, CategoryMasterDto.class); model.addAttribute("categoryMasterDtoResponse",dto); return "admin/addCategory"; } @RequestMapping(value=UPDATE_CATEGORY_MASTER, method = RequestMethod.POST) public String updateCategoryMaster(@ModelAttribute("categoryMasterDto") CategoryMasterDto categoryMasterDto, ModelMap model,HttpServletRequest request) throws IOException { RestTemplate restTemplate = new RestTemplate(); String categoryMasterDtoResponse = restTemplate.postForObject(URI+UPDATE_CATEGORY_MASTER, categoryMasterDto,String.class); ObjectMapper mapper = new ObjectMapper(); CategoryMasterDto dto = mapper.readValue(categoryMasterDtoResponse, CategoryMasterDto.class); model.addAttribute("categoryMasterDtoResponse",dto); return "admin/addCategory"; } //AJAX CALL FOR UPDATE CATEGORY STATUS @RequestMapping(value=UPDATE_CATEGORY_STATUS, method = RequestMethod.POST,consumes= MediaType.APPLICATION_JSON_VALUE) public @ResponseBody String updateCategoryStatus(@RequestBody CategoryMasterDto categoryMasterDto) throws IOException { RestTemplate restTemplate = new RestTemplate(); System.out.println("in controller method"); String categoryMasterDtoResponse = restTemplate.postForObject(URI+UPDATE_CATEGORY_MASTER, categoryMasterDto,String.class); return "admin/addCategory"; } } <file_sep>/src/main/java/com/aits/model/ProductMaster.java package com.aits.model; import java.util.List; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.ObjectIdGenerators; @Entity @Table(name = "Product_Master") @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class,property="productMasterId",scope = ProductMaster.class) public class ProductMaster { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ProductMaster_Id") private int productMasterId; @Column(name = "ProductMaster_Name", length = 100) private String productMasterName; @Column(name = "Is_Active", length = 2) private String isActive; @ManyToOne(targetEntity = SubCategoryMaster.class, cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE }) @JoinColumn(name = "Fk_SubCategoryMasterId") private SubCategoryMaster subCategoryMaster; // Bidirectional Relationship with SubProductMaster @OneToMany(targetEntity = SubProductMaster.class, cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE }, mappedBy = "productMaster") private Set<SubProductMaster> subProductMasterSet; @Transient private List<ProductMaster> productMasterList; public int getProductMasterId() { return productMasterId; } public void setProductMasterId(int productMasterId) { this.productMasterId = productMasterId; } public String getProductMasterName() { return productMasterName; } public void setProductMasterName(String productMasterName) { this.productMasterName = productMasterName; } public String getIsActive() { return isActive; } public void setIsActive(String isActive) { this.isActive = isActive; } public SubCategoryMaster getSubCategoryMaster() { return subCategoryMaster; } public void setSubCategoryMaster(SubCategoryMaster subCategoryMaster) { this.subCategoryMaster = subCategoryMaster; } public Set<SubProductMaster> getSubProductMasterSet() { return subProductMasterSet; } public void setSubProductMasterSet(Set<SubProductMaster> subProductMasterSet) { this.subProductMasterSet = subProductMasterSet; } public List<ProductMaster> getProductMasterList() { return productMasterList; } public void setProductMasterList(List<ProductMaster> productMasterList) { this.productMasterList = productMasterList; } } <file_sep>/src/main/java/com/aits/model/SubCategoryMaster.java package com.aits.model; import java.util.List; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.ObjectIdGenerators; @Entity @Table(name="SubCategory_Master") @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="subCategoryMasterId",scope = SubCategoryMaster.class) public class SubCategoryMaster { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "SubCategoryMaster_Id") private int subCategoryMasterId; @Column(name = "SubCategoryMaster_Name",length=100) private String subCategoryMasterName; @Column(name="Is_Active",length=2) private String isActive; @ManyToOne(targetEntity = CategoryMaster.class, cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE }) @JoinColumn(name = "Fk_CategoryMasterId") private CategoryMaster categoryMaster; //BiDirectional Relationship with ProductMaster @OneToMany(targetEntity = ProductMaster.class,cascade = {CascadeType.DETACH,CascadeType.MERGE,CascadeType.REFRESH,CascadeType.REMOVE},mappedBy="subCategoryMaster") private Set<ProductMaster> productMasterSet; @Transient private List<SubCategoryMaster> subCategoryMasterList; public int getSubCategoryMasterId() { return subCategoryMasterId; } public void setSubCategoryMasterId(int subCategoryMasterId) { this.subCategoryMasterId = subCategoryMasterId; } public String getSubCategoryMasterName() { return subCategoryMasterName; } public void setSubCategoryMasterName(String subCategoryMasterName) { this.subCategoryMasterName = subCategoryMasterName; } public String getIsActive() { return isActive; } public void setIsActive(String isActive) { this.isActive = isActive; } public CategoryMaster getCategoryMaster() { return categoryMaster; } public void setCategoryMaster(CategoryMaster categoryMaster) { this.categoryMaster = categoryMaster; } /*public Set<ProductMaster> getProductMasterSet() { return productMasterSet; } public void setProductMasterSet(Set<ProductMaster> productMasterSet) { this.productMasterSet = productMasterSet; } */ public List<SubCategoryMaster> getSubCategoryMasterList() { return subCategoryMasterList; } public void setSubCategoryMasterList(List<SubCategoryMaster> subCategoryMasterList) { this.subCategoryMasterList = subCategoryMasterList; } } <file_sep>/src/main/java/com/aits/model/SubProductMasterDiscountMapper.java package com.aits.model; import java.util.Date; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Transient; import com.aits.FactoryClasses.JsonDateSerializer; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import com.fasterxml.jackson.databind.annotation.JsonSerialize; @Entity @Table(name = "SubProductMaster_DiscountMapper") @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class,property="subProductMasterDiscountMapperId",scope = SubProductMasterDiscountMapper.class) public class SubProductMasterDiscountMapper { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "SubProductMasterDiscountMapper_Id") private int subProductMasterDiscountMapperId; @JsonSerialize(using=JsonDateSerializer.class) @Column(name = "SubProductMasterDiscountMapper_FromDate", length = 50) private Date subProductMasterDiscountMapperFromDate; @JsonSerialize(using=JsonDateSerializer.class) @Column(name = "SubProductMasterDiscountMapper_ToDate", length = 50) private Date subProductMasterDiscountMapperToDate; @Column(name="Is_Active",length=2) private String isActive; @ManyToOne(targetEntity = SubProductMaster.class, cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE }) @JoinColumn(name = "Fk_SubProductId") private SubProductMaster subProductMaster; @ManyToOne(targetEntity = DiscountMaster.class, cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE }) @JoinColumn(name = "Fk_DiscountMasterId") private DiscountMaster discountMaster; @Transient private List<SubProductMasterDiscountMapper> subProductMasterDiscountMapperList; public int getSubProductMasterDiscountMapperId() { return subProductMasterDiscountMapperId; } public void setSubProductMasterDiscountMapperId(int subProductMasterDiscountMapperId) { this.subProductMasterDiscountMapperId = subProductMasterDiscountMapperId; } public Date getSubProductMasterDiscountMapperFromDate() { return subProductMasterDiscountMapperFromDate; } public void setSubProductMasterDiscountMapperFromDate(Date subProductMasterDiscountMapperFromDate) { this.subProductMasterDiscountMapperFromDate = subProductMasterDiscountMapperFromDate; } public Date getSubProductMasterDiscountMapperToDate() { return subProductMasterDiscountMapperToDate; } public void setSubProductMasterDiscountMapperToDate(Date subProductMasterDiscountMapperToDate) { this.subProductMasterDiscountMapperToDate = subProductMasterDiscountMapperToDate; } public SubProductMaster getSubProductMaster() { return subProductMaster; } public void setSubProductMaster(SubProductMaster subProductMaster) { this.subProductMaster = subProductMaster; } public DiscountMaster getDiscountMaster() { return discountMaster; } public void setDiscountMaster(DiscountMaster discountMaster) { this.discountMaster = discountMaster; } public List<SubProductMasterDiscountMapper> getSubProductMasterDiscountMapperList() { return subProductMasterDiscountMapperList; } public void setSubProductMasterDiscountMapperList( List<SubProductMasterDiscountMapper> subProductMasterDiscountMapperList) { this.subProductMasterDiscountMapperList = subProductMasterDiscountMapperList; } public String getIsActive() { return isActive; } public void setIsActive(String isActive) { this.isActive = isActive; } } <file_sep>/src/main/java/com/aits/controller/AdminDiscountManagementController.java package com.aits.controller; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.client.RestTemplate; import com.aits.constant.AppConstant; import com.aits.dto.CategoryMasterDto; import com.aits.dto.DiscountMasterDto; import com.aits.dto.StateMasterDto; import com.fasterxml.jackson.databind.ObjectMapper; @Controller public class AdminDiscountManagementController implements AppConstant { @RequestMapping(value=GET_DISCOUNT_LIST, method = RequestMethod.GET) public String getDiscount(Model model)throws Exception { model.addAttribute("discountMasterDto",new DiscountMasterDto()); RestTemplate restTemplate=new RestTemplate(); String discountListResponse=restTemplate.getForObject(URI+GET_DISCOUNT_LIST, String.class); DiscountMasterDto discountMasterDto=new ObjectMapper().readValue(discountListResponse, DiscountMasterDto.class); model.addAttribute("discountMasterList",discountMasterDto.getDiscountMasterList()); return "admin/addDiscount"; } @RequestMapping(value=ADD_DISCOUNT, method = RequestMethod.POST) public String addDiscount(@ModelAttribute("discountMasterDto")DiscountMasterDto discountMasterDto ,Model model)throws Exception { RestTemplate restTemplate = new RestTemplate(); String discountMasterResponse=restTemplate.postForObject(URI+ADD_DISCOUNT,discountMasterDto,String.class); DiscountMasterDto diMasterDto=new ObjectMapper().readValue(discountMasterResponse,DiscountMasterDto.class); model.addAttribute("discountMasterList",diMasterDto.getDiscountMasterList()); model.addAttribute("discountMasterDto",discountMasterDto); model.addAttribute("msg","Discount Saved Successfully!!"); return "admin/addDiscount"; } @RequestMapping(value=GET_DISCOUNT_INFO_BY_ID+"{discountMasterId}", method = RequestMethod.GET) public String getDiscountMasterInformationById(@PathVariable("discountMasterId") int discountMasterId,Model model)throws Exception { System.out.println("Inside Get Discount Master By Id"+discountMasterId); RestTemplate restTemplate=new RestTemplate(); String discountListResponse=restTemplate.getForObject(URI+GET_DISCOUNT_INFO_BY_ID+discountMasterId, String.class); DiscountMasterDto discountMasterDto=new ObjectMapper().readValue(discountListResponse, DiscountMasterDto.class); model.addAttribute("discountMasterList",discountMasterDto.getDiscountMasterList()); model.addAttribute("discountMasterDto", discountMasterDto); return "admin/addDiscount"; } @RequestMapping(value=UPDATE_DISCOUNT, method = RequestMethod.POST) public String updateDiscountMasterInformation(@ModelAttribute("discountMasterDto")DiscountMasterDto discountMasterDto ,Model model)throws Exception{ RestTemplate restTemplate = new RestTemplate(); String discountMasterDtoResponse = restTemplate.postForObject(URI+UPDATE_DISCOUNT, discountMasterDto,String.class); ObjectMapper mapper = new ObjectMapper(); DiscountMasterDto dto = mapper.readValue(discountMasterDtoResponse, DiscountMasterDto.class); model.addAttribute("discountMasterDto",dto); model.addAttribute("discountMasterList", dto.getDiscountMasterList()); return "admin/addDiscount"; } }
90a8eb7e8cf44533074259f3785a6c6d8e6e1b95
[ "Java" ]
16
Java
automaticinfotech/ECOMM
ed698f895654b5a1651d8b3f29fd88eb661527ba
2b1cc99e4c39a4fb36cac90ad8bab2077b81301e
refs/heads/master
<repo_name>ainc/awesome-jobs<file_sep>/app/controllers/user_info_controller.rb class UserInfoController < ApplicationController def index if user_signed_in? @jobs = current_user.watching_jobs.order(:created_at).paginate(page: params[:page]) @possible_jobs = Job.all.order(created_at: :desc).take(5) if current_user.is_employer @job = Job.new else @work = Work.new end end end def show @user = User.where('LOWER(username) = ?', params[:username].downcase).first if !@user redirect_to root_path else if @user.is_employer @jobs = @user.jobs.order(created_at: :desc) @job = Job.new else @works = @user.works.order(:title) @work = Work.new end end end end <file_sep>/app/models/work.rb class Work < ActiveRecord::Base before_validation :preval belongs_to :user validates :title, presence: :true, length: { maximum: 50 } validates :description, presence: :true, length: { maximum: 400 } validates :url, presence: :true, length: { maximum: 100 } private def preval if self.title self.title = self.title.strip end if self.description self.description = self.description.strip end if self.url self.url = self.url.strip.delete(' ') if !self.url.blank? if !self.url.start_with?('http://') and !self.url.start_with?('https://') and !self.url.start_with?('www.') self.url = 'http://' + self.url end end end end end <file_sep>/app/controllers/jobs_controller.rb class JobsController < ApplicationController before_filter :authenticate_user!, except: [:index, :show] def show @job = Job.where(id: params[:id]).first if !@job redirect_to root_path elsif user_signed_in? @watching = Watching.where(user: current_user, job: @job).first end end def edit @job = Job.where(user: current_user, id: params[:id]).first if !@job redirect_to show_user_path(username: current_user.username) end end def create if params[:job] j = Job.new(title: params[:job][:title], description: params[:job][:description], url: params[:job][:url], user: current_user) respond_to do |format| if current_user.is_employer and j.save format.html { redirect_to show_job_path(id: j.id) } format.js { @vals = {success: true, url: show_user_path(username: current_user.username) } } else format.html { redirect_to show_user_path(username: current_user.username) } format.js { @vals = {success: false, job: j} } end end else redirect_to root_path end end def destroy j = Job.where(user: current_user, id: params[:id]).first respond_to do |format| if j and j.destroy format.html { redirect_to show_user_path(username: current_user.username) } else format.html { redirect_to show_user_path(username: current_user.username) } end end end def update j = Job.where(user: current_user, id: params[:id]).first respond_to do |format| if params[:job] and j and j.update(title: params[:job][:title], description: params[:job][:description], url: params[:job][:url]) format.html { redirect_to show_user_path(username: current_user.username) } format.js { @vals = { success: true, url: show_user_path(username: current_user.username) } } else format.html { redirect_to show_user_path(username: current_user.username) } format.js { @vals = { success: false, job: j } } end end end end <file_sep>/db/seeds.rb # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) # Based on the Trello comments hagan = User.new(username: 'hagan', password: ENV['<PASSWORD>'], email: '<EMAIL>', name: '<NAME>', company: 'Durham Labs', is_employer: true) hagan.skip_confirmation! hagan.save! hagan_job = Job.new(user: hagan, title: 'Engineer', description: 'Doing some engineering.' ,url: 'http://insiderlouisville.com/startups/cool-stuff/fred-durham-wants-play-food-robots-part-two-robots/') hagan_job.save! completeset = User.new(username: 'garydarna', password: ENV['<PASSWORD>'], email: '<EMAIL>', name: '<NAME>', company: 'CompleteSet', is_employer: true) completeset.skip_confirmation! completeset.save! completeset_job = Job.new(user: completeset, title: 'Software Engineer, iOS at CompleteSet', description: "RESPONSIBILITIES\n - Collaborate around the creation of new and existing features\n - Implement beautiful user interfaces\n") completeset_job.save! earthineer = User.new(username: 'danadams', password: ENV['<PASSWORD>'], email: '<EMAIL>', name: '<NAME>', company: 'Earthineer', is_employer: true) earthineer.skip_confirmation! earthineer.save! earthineer_job = Job.new(user: earthineer, title: 'PHP Developer', description: "PHP developer to work with on an equity basis. Slim micro framework, eloquent ORM, handlebars, twig", url: 'http://earthineer.com/market') earthineer_job.save! leancor = User.new(username: 'bengreen', password: ENV['<PASSWORD>'], email: '<EMAIL>', name: '<NAME>', company: 'Leancor', is_employer: true) leancor.skip_confirmation! leancor.save! leancor_job = Job.new(user: leancor, title: 'Web Developer', description: "PHP 5.0 or later, Cake PHP/MVC framework, HTML/XHTML, CSS, Ajax, JQuery and Javascript", url: 'http://www.leancor.com/careers/') leancor_job.save! rector = User.new(username: 'davidrector', password: ENV['<PASSWORD>'], email: '<EMAIL>', name: '<NAME>', is_employer: false) rector.skip_confirmation! rector.save! lagrone = User.new(username: 'jameslagrone', password: ENV['<PASSWORD>'], email: '<EMAIL>', name: '<NAME>', is_employer: false) lagrone.skip_confirmation! lagrone.save! jacoby = User.new(username: 'benjacoby', password: ENV['<PASSWORD>'], email: '<EMAIL>', name: '<NAME>', is_employer: true) jacoby.skip_confirmation! jacoby.save! jacoby_job = Job.new(user: jacoby, title: 'Web Software Engineer (Full-Stack)', description: 'We are currently seeking an engineer for full-stack web development.', url: 'https://worknola.com/revelry-labs-llc/web-software-engineer-full-stack') jacoby_job.save! pridemore = User.new(username: 'jamiepridemore', password: ENV['<PASSWORD>'], email: '<EMAIL>', name: '<NAME>', is_employer: true) pridemore.skip_confirmation! pridemore.save! pridemore_job = Job.new(user: pridemore, title: 'PHP Developer', description: 'Must be able to write clean, well-documented code. Must be willing to show up on time every day. Must be an expert in CSS, HTML5, Javascript & libraries, SQL, and not be boring.', url: 'https://www.facebook.com/burritosonyourfeet/posts/10154856813705246') pridemore_job.save! howard = User.new(username: 'shanehoward', password: ENV['<PASSWORD>'], email: '<EMAIL>', name: '<NAME>', is_employer: true) howard.skip_confirmation! howard.save! howard_job = Job.new(user: howard, title: 'Web Developer', description: '.NET/ColdFusion') howard_job.save! <file_sep>/app/controllers/application_controller.rb class ApplicationController < ActionController::Base # Devise param config before_action :configure_permitted_parameters, if: :devise_controller? # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception def error_404 respond_to do |format| format.html { render template: 'errors/error_404', layout: 'layouts/application', status: 404 } format.all { render nothing: true, status: 404 } end end def error_422 respond_to do |format| format.html { render template: 'errors/error_422', layout: 'layouts/application', status: 500 } format.all { render nothing: true, status: 500} end end def error_500 respond_to do |format| format.html { render template: 'errors/error_500', layout: 'layouts/application', status: 500 } format.all { render nothing: true, status: 500} end end private def configure_permitted_parameters devise_parameter_sanitizer.for(:sign_in) << :login devise_parameter_sanitizer.for(:sign_up) << :name devise_parameter_sanitizer.for(:sign_up) << :is_employer devise_parameter_sanitizer.for(:sign_up) << :username devise_parameter_sanitizer.for(:sign_up) << :name devise_parameter_sanitizer.for(:sign_up) << :company devise_parameter_sanitizer.for(:sign_up) << :website devise_parameter_sanitizer.for(:sign_up) << :address devise_parameter_sanitizer.for(:sign_up) << :phone devise_parameter_sanitizer.for(:sign_up) << :email devise_parameter_sanitizer.for(:account_update) << :name devise_parameter_sanitizer.for(:account_update) << :description devise_parameter_sanitizer.for(:account_update) << :company devise_parameter_sanitizer.for(:account_update) << :website devise_parameter_sanitizer.for(:account_update) << :address devise_parameter_sanitizer.for(:account_update) << :phone devise_parameter_sanitizer.for(:account_update) << :avatar devise_parameter_sanitizer.for(:account_update) << :remove_avatar devise_parameter_sanitizer.for(:account_update) << :username devise_parameter_sanitizer.for(:account_update) << :email if user_signed_in? and !current_user.is_employer devise_parameter_sanitizer.for(:account_update) << :resume devise_parameter_sanitizer.for(:account_update) << :remove_resume end end end <file_sep>/test/models/job_test.rb require 'test_helper' class JobTest < ActiveSupport::TestCase # test "the truth" do # assert true # end test 'save valid job' do j = Job.new(title: 'A', description: 'A', user_id: 1) assert j.save end test 'no saving invalid jobs' do j = Job.new(description: 'A', user_id: 1) assert !j.save j2 = Job.new(title: 'A', user_id: 1) assert !j2.save end end <file_sep>/app/controllers/registrations_controller.rb class RegistrationsController < Devise::RegistrationsController def create if !verify_recaptcha flash.delete :recaptcha_error build_resource(sign_up_params) resource.valid? resource.errors.add(:base, I18n.t('recaptcha_error')) clean_up_passwords(resource) render :new else flash.delete :recaptcha_error super end end def update if params[:user][:password] and params[:user][:password].length > 0 and params[:user][:password].blank? resource.errors.add(:password, t('password_spaces_error')) render :edit else super end end end <file_sep>/README.md Awesome Jobs ====== Welcome to the source code for the Awesome Jobs bulletin! Getting Started ----------- This project was written with Ruby on Rails, so if you're unfamiliar with terminology such as "MVC Architecture" or "Agile Web Development", then you may want to read about the basics of Rails (or any other kind of web development that resembles Rails), because there are so many directories in such kinds of projects like this one that it's quite easy to get lost at first. You'll notice that most of the code here reads either like English or basic SQL statements (thanks to Ruby), so the comments here aren't too intensive. This is to prevent littering the files with gobbledygook to make it read easier, but if there are any statements that aren't quite clear, alert me and I'll update the code accordingly. Let's dive into the juicy part, shall we? A Few Specifics ------------ When people create their accounts, they need to confirm their email addresses. Also, when an email address is to be changed, it also needs to be confirmed. Because of this along with the reCAPTCHA that I decided to implement, you need to set certain environment variables in a file called *config/application.yml* (you will need to create this file) in order to get anything involving users up and running without interacting with the console. Those variables are as follows: * **RECAPTCHA_PUBLIC_KEY** * **RECAPTCHA_PRIVATE_KEY** * **GMAIL_USERNAME** * **GMAIL_PASSWORD** Also, this application uses the Postgres database adapter, so in order to run this locally, you have to have Postgres installed on your machine. Don't forget to create the databases defined in *config/database.yml*, otherwise none of this is going to work. The easiest way to run this application is as follows: * Start Postgres (should be via a native application). * Change to the *jobs* directory. * Run *bundle* in the command line if you haven't already. * Apply the database schema to the Postgres database by running *rake db:migrate* in the command line. * Start the Rails server by running *rails s* in the command line. * Navigate to *localhost:3000* in a web browser. One more thing: every single piece of English text in this application that is presented to the user can be found in one of the files in the *config/locales* directory. Models (*app/models*) ------------ This project contains the following model objects as well as their (important) properties: * **Job**: A job opening (creatable only by employers). * **Description**: A short description of the job opening. Must be present and is limited to 1000 characters. * **Title**: The title of the opening. Must be present and is limited to 50 characters. * **URL**: The URL of the work. Is limited to 100 characters. * **User**: The user who created the opening. * **User**: A site user. * **Address**: The address that the user decides to make public. Limited to 40 characters. * **Avatar**: The avatar of the user. * **Company**: The company that the user represents. Limited to 40 characters. * **Description**: A short description of the user. Limited to 500 characters. * **Email**: The email address of the user. * **Is Employer**: Whether or not the user is an employer. If the user is not an employer, then the user is a programmer. * **Name**: The name of the user. Must have length between or equal to one of 5 and 40 characters. * **Phone**: The contact phone number for the user. Limited to 20 characters. * **Resume**: The resume of the user. Can only be uploaded by programmers. * **Username**: The username chosen by the user. Must have length between or equal to one of 3 and 15 characters. * **Website**: The user's website. Limited to 100 characters. * **Watching**: A relationship between a user and a job that signifies that a certain user is watching a certain job. * **Job**: The job in question. * **User**: The user in question. * **Work**: A finished piece of work (creatable only by programmers). * **Description**: A short description of the work. Must be present and is limited to 400 characters. * **Title**: The title of the work. Must be present and is limited to 50 characters. * **URL**: The URL of the work. Must be present and is limited to 100 characters. * **User**: The user who created the work. In addition to these properties, all model objects contain **Created At** and **Updated At** properties, as well as any other ones provided by external gems. All the validation specifications can be found in each model's respective file in the model directory. Views (*app/views*) ------------ Every view template in this directory is of one of three extensions: ".html.haml", ".js.erb", and ".html.erb". Every HAML file (".html.haml") is a standard HTML template written with the HAML preprocessor. Every Ruby-Embedded Javascript file (".js.erb") is a Javascript file for an AJAX request. Every Ruby-Embedded HTML file (".html.erb") is also a standard HTML template, but just one of the templates that didn't need much modification. Each file is located in the corresponding controller's subdirectory. Controllers (*app/controllers*) ------------ Here's a quick rundown of the various controllers for this project: * **Browse**: Handles all views involving browsing. * **Confirmations**: Overrides the default Devise implementation of confirmations. * **Contact**: Handles one user communicating to another via a contact page. * **Errors**: Provides custom 404, 422, and 500 error pages. * **Jobs**: Handles everything involving jobs management. * **Registrations**: Overrides the default Devise implementation of user registration. * **Sessions**: Overrides the default Devise implementation of session management. * **User Info**: Handles the display of user information. * **Watchings**: Handles everything involving watchings management. * **Works**: Handles everything involving works management. Extra Possibly-Helpful Info ------------ * All of this application's routes can be found in *config/routes.rb*. * Supporting stylesheets, javascripts, and images are found in *app/assets*. ~ Alek<file_sep>/app/controllers/browse_controller.rb class BrowseController < ApplicationController def programmers @users = User.where(is_employer: false).order(:name).paginate(page: params[:page]) end def employers @users = User.where(is_employer: true).order(:name).paginate(page: params[:page]) end def programmer_search @q = params[:q] if @q and [email protected]? @q = @q.strip @users = User.where(is_employer: false).where("LOWER(name) LIKE LOWER(?) OR LOWER(description) LIKE LOWER(?)", "%#{@q}%", "%#{@q}%").order(created_at: :desc).paginate(page: params[:page]) else redirect_to show_programmers_path end end def employer_search @q = params[:q] if @q and [email protected]? @q = @q.strip @users = User.where(is_employer: false).where("LOWER(name) LIKE LOWER(?) OR LOWER(description) LIKE LOWER(?) OR LOWER(company) LIKE LOWER(?)", "%#{@q}%", "%#{@q}%", "%#{@q}%").order(created_at: :desc).paginate(page: params[:page]) else redirect_to show_employers_path end end def jobs @jobs = Job.all.order(created_at: :desc).paginate(page: params[:page]) if user_signed_in? @watching_jobs = current_user.watching_jobs.order(:created_at).paginate(page: params[:watching_page]) end end def job_search @q = params[:q] if @q and [email protected]? @q = @q.strip @jobs = Job.where("LOWER(title) LIKE LOWER(?) OR LOWER(description) LIKE LOWER(?)", "%#{@q}%", "%#{@q}%").order(created_at: :desc).paginate(page: params[:page]) else redirect_to show_programmers_path end end end <file_sep>/app/controllers/watchings_controller.rb class WatchingsController < ApplicationController before_filter :authenticate_user! def create w = Watching.new(user: current_user, job_id: params[:id]) j = Job.where(id: params[:id]).first respond_to do |format| if j and w.save display = view_context.link_to('<span class="glyphicon glyphicon-eye-close"></span>'.html_safe, destroy_watching_path(id: w.id), class: 'btn btn-lg btn-danger', method: :delete, remote: true) format.html { redirect_to show_job_path(id: params[:id]) } format.js { @vals = { success: true, display: display } } else format.html { redirect_to show_job_path(id: params[:id]) } format.js { @vals = { success: false} } end end end def destroy w = Watching.where(user: current_user, id: params[:id]).first respond_to do |format| if w and w.destroy display = view_context.link_to('<span class="glyphicon glyphicon-eye-open"></span>'.html_safe, create_watching_path(id: w.job_id), class: 'btn btn-lg btn-primary', method: :post, remote: true) format.html { redirect_to show_user_path(username: current_user.username) } format.js { @vals = { success: true, display: display } } else format.html { redirect_to show_user_path(username: current_user.username) } format.js { @vals = { success: false } } end end end end <file_sep>/app/controllers/confirmations_controller.rb class ConfirmationsController < Devise::ConfirmationsController def new if user_signed_in? redirect_to root_path else super end end def create if user_signed_in? redirect_to root_path else super end end end <file_sep>/app/models/job.rb class Job < ActiveRecord::Base before_validation :preval before_create :not_too_many belongs_to :user validates :title, presence: :true, length: { maximum: 50 } validates :description, presence: :true, length: { maximum: 1000 } validates :url, length: { maximum: 100 } private def preval if self.title self.title = self.title.strip end if self.description self.description = self.description.strip end if self.url self.url = self.url.strip.delete(' ') if !self.url.blank? if !self.url.start_with?('http://') and !self.url.start_with?('https://') and !self.url.start_with?('www.') self.url = 'http://' + self.url end end end end def not_too_many count = Job.where(user_id: self.user_id, created_at: 1.hour.ago..DateTime.now).count count <= 10 end end <file_sep>/lib/file_size_validator.rb # lib/file_size_validator.rb # Based on: https://gist.github.com/795665 class FileSizeValidator < ActiveModel::EachValidator MESSAGES = { :is => :wrong_size, :minimum => :size_too_small, :maximum => :size_too_big }.freeze CHECKS = { :is => :==, :minimum => :>=, :maximum => :<= }.freeze DEFAULT_TOKENIZER = lambda { |value| value.split(//) } RESERVED_OPTIONS = [:minimum, :maximum, :within, :is, :tokenizer, :too_short, :too_long] def initialize(options) if range = (options.delete(:in) || options.delete(:within)) raise ArgumentError, ":in and :within must be a Range" unless range.is_a?(Range) options[:minimum], options[:maximum] = range.begin, range.end options[:maximum] -= 1 if range.exclude_end? end super end def check_validity! keys = CHECKS.keys & options.keys if keys.empty? raise ArgumentError, 'Range unspecified. Specify the :within, :maximum, :minimum, or :is option.' end keys.each do |key| value = options[key] unless value.is_a?(Integer) && value >= 0 raise ArgumentError, ":#{key} must be a nonnegative Integer" end end end def validate_each(record, attribute, value) raise(ArgumentError, "A CarrierWave::Uploader::Base object was expected") unless value.kind_of? CarrierWave::Uploader::Base value = (options[:tokenizer] || DEFAULT_TOKENIZER).call(value) if value.kind_of?(String) CHECKS.each do |key, validity_check| next unless check_value = options[key] value ||= [] if key == :maximum value_size = value.size next if value_size.send(validity_check, check_value) errors_options = options.except(*RESERVED_OPTIONS) errors_options[:file_size] = help.number_to_human_size check_value default_message = options[MESSAGES[key]] errors_options[:message] ||= default_message if default_message record.errors.add(attribute, MESSAGES[key], errors_options) end end def help Helper.instance end class Helper include Singleton include ActionView::Helpers::NumberHelper end end <file_sep>/app/models/user.rb require 'file_size_validator' class User < ActiveRecord::Base attr_accessor :login before_validation :preval mount_uploader :avatar, AvatarUploader mount_uploader :resume, ResumeUploader # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :confirmable, :database_authenticatable, :lockable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_many :jobs, dependent: :destroy has_many :works, dependent: :destroy has_many :watchings, dependent: :destroy has_many :watching_jobs, through: :watchings, source: :job validate :good_password validates :username, length: {minimum: 3, maximum: 15}, :uniqueness => { :case_sensitive => false }, format: /\A[_\.A-Za-z0-9]+\Z/ validates :name, length: { minimum: 5, maximum: 40 } validates :company, length: { maximum: 40 } validates :description, length: { maximum: 500 } validates :address, length: { maximum: 40 } validates :phone, length: { maximum: 20 } validates :website, length: { maximum: 100 } validates :avatar, :file_size => { :maximum => 0.5.megabytes.to_i } validates :resume, :file_size => { :maximum => 1.megabytes.to_i } def self.noncaptcha_attempts 3 end private def preval if self.name self.name = self.name.strip end if self.company self.company = self.company.strip end if self.description self.description = self.description.strip end if self.address self.address = self.address.strip end if self.phone self.phone = self.phone.strip end if self.website self.website = self.website.strip.delete(' ') if !self.website.blank? if !self.website.start_with?('http://') and !self.website.start_with?('https://') and !self.website.start_with?('www.') self.website = 'http://' + self.website end end end end def good_password if password_confirmation and password_confirmation.length > 0 and password_confirmation.blank? errors.add(:password, '<PASSWORD>.') end end def self.find_first_by_auth_conditions(warden_conditions) conditions = warden_conditions.dup if login = conditions.delete(:login) where(conditions).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first else where(conditions).first end end end <file_sep>/app/controllers/works_controller.rb class WorksController < ApplicationController before_filter :authenticate_user! def edit @work = Work.where(user: current_user, id: params[:id]).first if !@work redirect_to show_user_path(username: current_user.username) end end def create if params[:work] w = Work.new(user: current_user, title: params[:work][:title], description: params[:work][:description], url: params[:work][:url]) respond_to do |format| if !current_user.is_employer and w.save format.html { redirect_to show_user_path(id: current_user.id) } format.js { @vals = { success: true, url: show_user_path(username: current_user.username) } } else format.html { redirect_to show_user_path(username: current_user.username) } format.js { @vals = { success: false, work: w } } end end else redirect_to root_path end end def update w = Work.where(user: current_user, id: params[:id]).first respond_to do |format| if params[:work] and w and w.update(title: params[:work][:title], description: params[:work][:description], url: params[:work][:url]) format.html { redirect_to show_user_path(id: current_user.id) } format.js { @vals = { success: true, url: show_user_path(username: current_user.username) } } else format.html { redirect_to show_user_path(username: current_user.username) } format.js { @vals = { success: false, work: w } } end end end def destroy w = Work.where(user: current_user, id: params[:id]).first respond_to do |format| if w and w.destroy format.html { redirect_to show_user_path(username: current_user.username) } else format.html { redirect_to show_user_path(username: current_user.username) } end end end end <file_sep>/app/controllers/contact_controller.rb class ContactController < ApplicationController before_filter :authenticate_user! def contact_page if params[:username] @user = User.where('LOWER(username) = ?', params[:username].downcase).first end if !@user or @user == current_user redirect_to root_path end end def send_contact_request @errors = [] can_send = true if params[:message] @message = params[:message].strip end if params[:username] @user = User.where('LOWER(username) = ?', params[:username].downcase).first end if @message and @message.blank? @errors << I18n.t('message_cant_be_blank') @message_failed = true can_send = false end if !verify_recaptcha @errors << I18n.t('recaptcha_error') can_send = false end if can_send and @user and @user != current_user ContactMailer.contact_form(current_user, @user, @message).deliver redirect_to root_path, notice: I18n.t('message_sent') else if @user render :contact_page else redirect_to root_path end end end end <file_sep>/app/models/watching.rb class Watching < ActiveRecord::Base belongs_to :user belongs_to :job validates_uniqueness_of :user_id, scope: [:job_id] end <file_sep>/test/models/watching_test.rb require 'test_helper' class WatchingTest < ActiveSupport::TestCase # test "the truth" do # assert true # end test 'create normal watching' do w = Watching.new(user_id: 1, job_id: 1) assert w.save end test 'no saving duplicate watchings' do w = Watching.new(user_id: 2, job_id: 2) assert w.save w2 = Watching.new(user_id: 2, job_id: 2) assert !w2.save end end <file_sep>/test/models/work_test.rb require 'test_helper' class WorkTest < ActiveSupport::TestCase # test "the truth" do # assert true # end test 'save valid work' do w = Work.new(title: 'A', description: 'A', url: 'google.com', user_id: 1) assert w.save end test 'no saving invalid works' do w = Work.new(description: 'A', url: 'google.com', user_id: 1) assert !w.save w2 = Work.new(title: 'A', url: 'google.com', user_id: 1) assert !w2.save w3 = Work.new(title: 'A', description: 'A', user_id: 1) assert !w3.save end end <file_sep>/app/helpers/application_helper.rb module ApplicationHelper def flash_errors(object) if resource and resource.errors and resource.errors.count > 0 or !flash[:alert].blank? output = '' output += '<div class="alert alert-danger">' output += '<button type="button" class="close" data-dismiss="alert" aria-hidden="true"> &times;</button>' output += "<h4 class='text-center'>#{I18n.t('error')}</h4>" object.errors.full_messages.each do |message| output += "<p class='text-center'>#{message}</p>" end if !flash[:alert].blank? output += "<p class='text-center'>#{flash[:alert]}</p>" end output += '</div>' output += "<script type='text/javascript'>$('.alert').alert();</script>" output.html_safe else '' end end def error_for_field(resource, symbols, &proc) error = false symbols.each do |s| error = resource.errors[s].first.nil? ? error : true end output = '' if error output += "<div class='form-group has-error has-feedback'>" output += "#{proc.yield}" output += "<span class='glyphicon glyphicon-remove form-control-feedback'></span>" output += "</div>" else output += "<div class='form-group'>" output += "#{proc.yield}" output += "</div>" end output.html_safe end def resource_errors! output = "" if resource and resource.errors and resource.errors.count > 0 output += "<div class='alert alert-danger'> <script type='text/javascript'> $('.alert').alert(); </script> <button type='button' class='close' data-dismiss='alert' aria-hidden='true'> #{'&times;'.html_safe} </button> <h4 class='text-center'> #{I18n.t('error')}</h4>" resource.errors.full_messages.uniq.each do |message| output += "<p class='text-center'>#{message}</p>" end output += "</div>" end output.html_safe end end <file_sep>/app/controllers/sessions_controller.rb class SessionsController < Devise::SessionsController def new @disable_alerts = true if sign_in_params and sign_in_params[:login] u = User.where(["LOWER(username) = :value", { :value => sign_in_params[:login].downcase }]).first if u @needs_captcha = u.failed_attempts >= User.noncaptcha_attempts end end super end def create u = User.where(["LOWER(username) = :value", { :value => params[:user][:login].downcase }]).first if u and u.failed_attempts >= User.noncaptcha_attempts if verify_recaptcha super else self.resource = resource_class.new(sign_in_params) clean_up_passwords(resource) if u.failed_attempts != User.noncaptcha_attempts resource.errors.add(:base, t('recaptcha_error')) else resource.errors.add(:base, t('recaptcha_prompt')) end @needs_captcha = true respond_with_navigational(resource) { render :new } end else super end end end <file_sep>/app/mailers/contact_mailer.rb class ContactMailer < ActionMailer::Base default from: "<EMAIL>" def contact_form(sender, recipient, message) @user = sender @message = message if @message.size > 4000 @message = @message[0..4000] + " \n #{I18n.t('message_truncated')}" end mail(to: recipient.email, subject: "#{I18n.t('contact_request')}: #{@user.username}") end end <file_sep>/config/routes.rb Rails.application.routes.draw do devise_for :users, controllers: {registrations: 'registrations', sessions: 'sessions', confirmations: 'confirmations'}, path: '', :skip => [:confirmations, :passwords] devise_scope :user do get '/new_confirmation' => 'confirmations#new', :as => :new_user_confirmation post '/confirmation' => 'confirmations#create', :as => :user_confirmation get '/confirmation' => 'confirmations#show', :as => :show_user_confirmation get '/new_password' => '<PASSWORD>', :as => :new_user_password post '/password' => '<PASSWORD>', :as => :user_password get '/password' => '<PASSWORD>', :as => :edit_user_password put '/password' => '<PASSWORD>', :as => :update_user_password end controller :application do get '404' => :error_404 get '422' => :error_422 get '500' => :error_500 end controller :browse do get '/programmers' => :programmers, as: 'show_programmers' get '/employers' => :employers, as: 'show_employers' get '/programmer_search' => :programmer_search, as: 'search_programmers' get '/employer_search' => :employer_search, as: 'search_employers' get '/job_search' => :job_search, as: 'search_jobs' end controller :contact do get '/user/:username/c' => :contact_page, as: 'show_user_contact_page' post '/contact' => :send_contact_request, as: 'send_contact_request' end controller :jobs do post '/job/create' => :create, as: 'create_job' delete '/job/destroy' => :destroy, as: 'destroy_job' get '/job/:id' => :show, as: 'show_job' get '/job/:id/edit' => :edit, as: 'edit_job' patch '/job/:id/update' => :update, as: 'update_job' end controller :user_info do get '/user/:username' => :show, as: 'show_user' end controller :watchings do post '/watching/create' => :create, as: 'create_watching' delete '/watching/destroy' => :destroy, as: 'destroy_watching' end controller :works do post '/work/create' => :create, as: 'create_work' delete '/work/:id/destroy' => :destroy, as: 'destroy_work' get '/work/:id/edit' => :edit, as: 'edit_work' patch '/work/:id/update' => :update, as: 'update_work' end root 'browse#jobs' # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" # root 'welcome#index' # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end end
cc203a23c7eda485ba56117a2f9c621006d5f47b
[ "Markdown", "Ruby" ]
23
Ruby
ainc/awesome-jobs
3db9cd3c89ec4a4d5190231f0198dd48751ca40c
665a8163e1ba0b4033c3dcecdba05b741ca77f42
refs/heads/master
<repo_name>Ibuki-Suika/DPlayer-node<file_sep>/README.md # DPlayer backend > Node.js backend for [DPlayer](https://github.com/DIYgod/DPlayer) ## Usage ### Start ```shell docker-compose build docker-compose pull docker-compose up # -d for run it in the background ``` ### Data & logs Database data: `~/dplayer/db` DPlayer logs: `~/dplayer/logs` PM2 logs: `~/dplayer/pm2logs` ### Import ```shell mv dans.json ~/dplayer/db/backup/dans.json docker exec dplayernode_mongo_1 mongoimport -d danmaku -c dans --file /data/db/backup/dans.json ``` ### Export ```shell docker exec dplayernode_mongo_1 mongoexport -d danmaku -c dans -o /data/db/backup/dans.json cat ~/dplayer/db/backup/dans.json ``` ### Stop ```shell docker-compose stop ``` ## Communication Groups [Telegram Group](https://t.me/adplayer) [QQ Group: 415835947](https://shang.qq.com/wpa/qunwpa?idkey=<KEY>) ## Related Projects - [DPlayer](https://github.com/DIYgod/DPlayer) - [DPlayer-data(weekly backup for api.prprpr.me/dplayer)](https://github.com/DIYgod/DPlayer-data) - [DPlayer-for-typecho](https://github.com/volio/DPlayer-for-typecho) - [Hexo-tag-dplayer](https://github.com/NextMoe/hexo-tag-dplayer) - [DPlayer_for_Z-BlogPHP](https://github.com/fghrsh/DPlayer_for_Z-BlogPHP) - [纸飞机视频区插件(DPlayer for Discuz!)](https://coding.net/u/Click_04/p/video/git) - [dplayer_py_backend](https://github.com/dixyes/dplayer_py_backend) - [dplayer_lua_backend](https://github.com/dixyes/dplayer_lua_backend) - [DPlayer for WordPress](https://github.com/BlueCocoa/DPlayer-WordPress) - [Vue-DPlayer](https://github.com/sinchang/vue-dplayer) ## LICENSE [The Star And Thank Author License (SATA)](https://github.com/DIYgod/DPlayer/blob/master/LICENSE)<file_sep>/routes/all.js var logger = require('../tools/logger'); var blank = require('../tools/blank'); module.exports = function (req, res, next) { if (req.headers.referer && blank(req.headers.referer)) { logger.info(`Reject all form ${req.headers.referer} for black referer.`); res.send(`{"code": 6, "msg": "black referer"}`); return; } res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild'); res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS'); res.header('Cache-control', 'no-cache'); if (req.method == 'OPTIONS') { res.send(200); } else { next(); } };<file_sep>/routes/video-bilibili.js var url = require('url'); var logger = require('../tools/logger'); var redis = require('../tools/redis'); var fetch = require('node-fetch'); var md5 = require('blueimp-md5'); var xml2js = require('xml2js'); var parseString = xml2js.parseString; var appkey = '<KEY>'; var secret = '1c15888dc316e05a15fdd0a02ed6584f'; function getData(cid, res, type) { var para = `cid=${cid}&from=miniplay&player=1&quality=2&type=mp4`; var sign = md5(`${para}${secret}`); var api = `http://interface.bilibili.com/playurl?${para}&sign=${sign}`; if (type === '1') { res.send(api); } else { fetch(api, { headers: {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36'}, }).then( response => response.text() ).then((data) => { parseString(data, { explicitArray: false }, function (err, result) { // res.send(result.video.durl.url.replace('http://', 'https://')); res.redirect(301, result.video.durl.url.replace('http://', 'https://')); }); } ).catch( e => logger.error("Bilibilib Error: getting data", e) ); } } module.exports = function (req, res) { var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress; var query = url.parse(req.url,true).query; var aid = query.aid; var cid = query.cid; var type = query.type; if (cid) { logger.info(`Bilibili cid2video ${cid}, IP: ${ip}`); getData(cid, res, type); } else { redis.client.get(`bilibiliaid2cid${aid}`, function(err, reply) { if (reply) { logger.info(`Bilibili aid2video ${aid} form redis, IP: ${ip}`); getData(reply, res, type); } else { logger.info(`Bilibili aid2video ${aid} form origin, IP: ${ip}`); fetch(`http://www.bilibili.com/widget/getPageList?aid=${aid}`).then( response => response.json() ).then((data) => { redis.set(`bilibiliaid2cid${aid}`, data[0].cid); getData(data[0].cid, res, type); } ).catch( e => logger.error("Bilibili aid2video Error: getting cid", e) ); } }); } };
7e188121d978ea62edd9d1afcb48ddfc7bb10640
[ "Markdown", "JavaScript" ]
3
Markdown
Ibuki-Suika/DPlayer-node
e796e2f71267867000f6531556321a124ae246e9
38cae29cecacc2934c2f7636836e0ab6cf5ec321
refs/heads/master
<repo_name>zhangchuheng123/PAT<file_sep>/1001.c #include <stdio.h> int main(int argc, char const *argv[]) { int a,b; int sum; int seperateSum[10]; int counter = 0; scanf("%d",&a); scanf("%d",&b); sum = a + b; // dealing with negative sign if (sum < 0) c{ printf("-"); sum = (- sum); } // seperate the sum the two do { seperateSum[counter++] = sum % 1000; sum = sum / 1000; } while (sum != 0); // output printf("%d", seperateSum[--counter]); while (counter > 0) { printf(",%03d", seperateSum[--counter]); } return 0; } <file_sep>/1003.c /* Emergency Use DFS to search the shortest path between two given points Sample input 5 6 0 2 1 2 1 5 3 0 1 1 0 2 2 0 3 1 1 2 1 2 4 1 3 4 1 Sample output 2 4 Frankly speaking, I have seen the code from my friend <NAME>(github) before I started coding this. I changed my mind from using Dijstra to using DFS after I saw the code. */ #include <stdio.h> #include <limits.h> #define MAX_NUM_OF_CITY 510 #define INF INT_MAX #define NOT_VISITED 0 #define VISITED 1 void init(); void DFS(int cur, int des, int len, int accGroup); int numOfCity, numOfRoad, currentCity, saveCity; int groupInCity[MAX_NUM_OF_CITY]; int dist[MAX_NUM_OF_CITY][MAX_NUM_OF_CITY]; int shortestCount, shortestLen, maxGroup; short label[MAX_NUM_OF_CITY]; int main(int argc, char const *argv[]) { init(); label[currentCity] = VISITED; DFS(currentCity, saveCity, 0, groupInCity[currentCity]); printf("%d %d", shortestCount, maxGroup); return 0; } void init() { int t1,t2,len; shortestCount = 0; shortestLen = INF; maxGroup = 0; scanf("%d%d%d%d", &numOfCity, &numOfRoad, &currentCity, &saveCity); for (int i = 0; i < numOfCity+1; ++i) { for (int j = 0; j < numOfCity+1; ++j) { dist[i][j] = INF; } } for (int i = 0; i < numOfCity; ++i) { scanf("%d", &groupInCity[i]); } for (int i = 0; i < numOfRoad; ++i) { scanf("%d%d%d", &t1, &t2, &len); dist[t1][t2] = len; dist[t2][t1] = len; } return; } void DFS(int cur, int des, int len, int accGroup) { if (cur == des) { if (len < shortestLen) { shortestLen = len; shortestCount = 1; maxGroup = accGroup; } else if (len == shortestLen) { shortestCount++; if (maxGroup < accGroup) { maxGroup = accGroup; } } return; } if (len > shortestLen) { return; } for (int i = 0; i < numOfCity; ++i) { if ((dist[cur][i] != INF) && (label[i] == NOT_VISITED)) { label[i] = VISITED; DFS(i, des, len + dist[cur][i], accGroup + groupInCity[i]); label[i] = NOT_VISITED; } } return; }<file_sep>/1009.c /* Product of polynomials http://www.patest.cn/contests/pat-a-practise/1009 Sample Input: 2 1 2.4 0 3.2 2 2 1.5 1 0.5 Sample output: 3 3 3.6 2 6.0 1 1.6 */ #include <stdio.h> #define MAX_EXPO 1010 #define DOUBLE_MAX_EXPO 2020 #define MAX_EXPO_TIGHT 1001 float a[MAX_EXPO],b[MAX_EXPO],product[DOUBLE_MAX_EXPO]; int main(int argc, char const *argv[]) { int k, expo, count; float coef; scanf("%d", &k); for (int i = 0; i < k; ++i) { scanf("%d%f", &expo, &coef); a[expo] = coef; } scanf("%d", &k); for (int i = 0; i < k; ++i) { scanf("%d%f", &expo, &coef); b[expo] = coef; } for (int i = 0; i < MAX_EXPO_TIGHT; ++i) { if (a[i] != 0) { for (int j = 0; j < MAX_EXPO_TIGHT; ++j) { if (b[j] != 0) { product[i+j] += a[i] * b[j]; } } } } count = 0; for (int i = 0; i < DOUBLE_MAX_EXPO; ++i) { if (product[i] != 0) { count++; } } printf("%d", count); for (int i = DOUBLE_MAX_EXPO; i >= 0; --i) { if (product[i] != 0) { printf(" %d %.1f", i, product[i]); } } return 0; } <file_sep>/1008.c /* Elevator Description: 6 sec move up one floor 4 sec move down one floor 5 sec stop start at 0th floor Example: 3 2 3 1 */ #include <stdio.h> #define UP_TIME 6 #define DOWN_TIME 4 #define STOP_TIME 5 int main(int argc, char const *argv[]) { int n; int nextFloor; int totalTime = 0; int currentFloor = 0; scanf("%d",&n); for (int i = 0; i < n; ++i) { scanf("%d",&nextFloor); if (nextFloor > currentFloor) { totalTime += (nextFloor - currentFloor) * UP_TIME; currentFloor = nextFloor; } else if (nextFloor < currentFloor) { totalTime += (currentFloor - nextFloor) * DOWN_TIME; currentFloor = nextFloor; } totalTime += STOP_TIME; } printf("%d", totalTime); return 0; }<file_sep>/README.md # PAT This folder is where PAT codes are put. <file_sep>/1005.c /* Spell it Right http://www.patest.cn/contests/pat-a-practise/1005 Sample input: 12345 Sample output: one five */ #include <stdio.h> #include <string.h> int main(int argc, char const *argv[]) { char ch; int sum = 0; const char NUMBER[][10] = {"zero","one","two","three","four","five","six","seven","eight","nine"}; int seperate[5]; int count = 0; ch = getchar(); while ((ch >= '0') && (ch <= '9')) { sum += (ch - '0'); ch = getchar(); } while (sum > 0) { seperate[count++] = sum % 10; sum /= 10; } printf("%s", NUMBER[seperate[--count]]); while (count > 0) { putchar(' '); printf("%s", NUMBER[seperate[--count]]); } return 0; }<file_sep>/1002.c /* A+B problem for polynomials sample input: 2 1 2.4 0 3.2 2 2 1.5 1 0.5 */ #include <stdio.h> int main(int argc, char const *argv[]) { int k; double co[1010] = {0.0}; int ex; double tmpCo; int counter = 0; for (int i = 0; i < 2; ++i) { scanf("%d", &k); for (int j = 0; j < k; ++j) { scanf("%d%lf", &ex, &tmpCo); co[ex] += tmpCo; } } for (int i = 0; i < 1010; ++i) { if (co[i] != 0.0) { counter++; } } printf("%d", counter); for (int i = 1009; i >= 0; --i) { if (co[i] != 0.0) { printf(" %d %.1lf", i, co[i]); } } return 0; }<file_sep>/1011.c /* World Cup Betting Sample Input 1.1 2.5 1.7 1.2 3.0 1.6 4.1 1.2 1.1 Sample Output T T W 37.98 */ #include <stdio.h> #define EPS 0.00001 int main(int argc, char const *argv[]) { float o1,o2,o3,profit; profit = 1; for (int i = 0; i < 3; ++i) { if (i != 0) { printf(" "); } scanf("%f%f%f", &o1, &o2, &o3); if ((o1 >= o2) && (o1 >= o3)) { profit *= o1; printf("W"); } else if ((o2 >= o1) && (o2 >= o3)) { profit *= o2; printf("T"); } else if ((o3 >= o1) && (o3 >= o2)) { profit *= o3; printf("L"); } } profit = (profit * 0.65 - 1)*2; printf(" %.2f", profit+EPS); return 0; }<file_sep>/1004.c /* Counting Leaves Sample input: 2 1 01 1 02 Sample output: 0 1 Sample input: 11 6 02 2 05 06 01 3 02 03 04 10 1 11 07 1 10 04 3 07 08 09 09 1 12 Sample output: 0 1 3 1 1 This is not a very good algorithm for the problem */ #include <stdio.h> #define MAX_NODES 100 #define ROOT_ID 1 #define NOT_LEAVES 0 #define LEAVES 1 #define INITIAL_FLAG 119 #define FLAG_1 0 #define FLAG_2 1 short father[MAX_NODES]; short isLeave[MAX_NODES]; short level[MAX_NODES]; short count[MAX_NODES]; short maxLevel; void DFS(short curNode, short curLevel); int main(int argc, char const *argv[]) { int n,m,k; short id,tmpid; // in case there's some node's id == 00 for (int i = 0; i < MAX_NODES; ++i) { father[i] = INITIAL_FLAG; } // Read and save the structure of the tree scanf("%d%d", &n, &m); for (int i = 0; i < m; ++i) { scanf("%hd%d", &id, &k); for (int j = 0; j < k; ++j) { scanf("%hd", &tmpid); father[tmpid] = id; } } // It should be a Breath-first Algorithm, but here // I just use Depth-first Algorithm for convience DFS(1,0); for (int i = 0; i < MAX_NODES; ++i) { if (isLeave[i] == LEAVES) { count[level[i]]++; } } printf("%d", count[0]); for (int i = 1; i <= maxLevel; ++i) { printf(" %d", count[i]); } return 0; } void DFS(short curNode, short curLevel) { level[curNode] = curLevel; int flag = FLAG_1; for (int i = 0; i < MAX_NODES; ++i) { if (father[i] == curNode) { flag = FLAG_2; DFS(i,curLevel+1); } } if (flag == FLAG_1) { isLeave[curNode] = LEAVES; if (maxLevel < curLevel) { maxLevel = curLevel; } } else { isLeave[curNode] = NOT_LEAVES; } }<file_sep>/1006.c /* Sign In and Sign Out http://www.patest.cn/contests/pat-a-practise/1006 Sample input: 3 CS301111 15:30:28 17:00:10 SC3021234 08:00:00 11:25:25 CS301133 21:45:00 21:58:40 Sample output: SC3021234 CS301133 */ #include <stdio.h> #include <stdlib.h> #define MAXN 10000 #define MAX_ID_LENGTH 16 struct time { int hour; int minute; int second; }; int calTotal(struct time t); int main(int argc, char const *argv[]) { int n; char* id_number[MAXN]; struct time t1,t2; int early,early_id,late,late_id; late = 0; t1.hour = 23; t1.minute = 59; t1.second = 59; early = calTotal(t1); scanf("%d",&n); for (int i = 0; i < n; ++i) { id_number[i] = malloc(MAX_ID_LENGTH*sizeof(char)); scanf("%s%d:%d:%d%d:%d:%d",id_number[i], &(t1.hour), &(t1.minute), &(t1.second), &(t2.hour), &(t2.minute), &(t2.second)); if (calTotal(t1) < early) { early = calTotal(t1); early_id = i; } if (calTotal(t2) > late) { late = calTotal(t2); late_id = i; } } printf("%s %s", id_number[early_id],id_number[late_id]); return 0; } int calTotal(struct time t) { return ((t.hour * 60) + t.minute) * 60 + t.second; }<file_sep>/1007.c /* 1007 Maximum Subsequence Sum sample input 10 -10 1 2 3 4 -5 -23 3 7 -21 sample output 10 1 4 sample input 4 -10 -5 -23 -21 sample output 0 -10 -21 */ #include <stdio.h> #define FLAG_NEXT 1 #define FLAG_NONE 0 #define ENDNUM_UNSET_FLAG -1 // if endNum is set, it is impossible that the last number will be negative long startNum, endNum, maxSum, curSum, n, curNum, ansStartNum; short flag; //set the next num to curNum if flag == FLAG_NEXT int main(int argc, char const *argv[]) { scanf("%ld", &n); flag = FLAG_NEXT; endNum = ENDNUM_UNSET_FLAG; maxSum = -1; //scan once for (int i = 0; i < n; ++i) { scanf("%ld", &curNum); // if there's a flag, assign the current integer as the start number // there is a flag if 1. it is the first number 2. last curSum < 0 //printf("Now dealing with %ld\n", curNum); if (flag == FLAG_NEXT) { if (i == 0) { ansStartNum = curNum; } startNum = curNum; flag = FLAG_NONE; //printf("Set %ld to startNum\n", curNum); } // there are 3 cases: 1. new maximum appears 2. not exceeding existed maximum but not negative 3. sum is negative if (curSum + curNum > maxSum) { curSum += curNum; maxSum = curSum; endNum = curNum; ansStartNum = startNum; //printf("Find max so far maxSum=%ld, startNum=%ld, endNum=%ld\n", maxSum, startNum, endNum); } else if (curSum + curNum >= 0) { curSum += curNum; //printf("Not the max but still couting, curSum=%ld\n", curSum); } else if (curSum + curNum < 0) { curSum = 0; flag = FLAG_NEXT; //printf("Sum is negative\n"); } } // if endNum is never set, all the interger must be negative if (endNum == ENDNUM_UNSET_FLAG) { maxSum = 0; endNum = curNum; } printf("%ld %ld %ld", maxSum, ansStartNum, endNum); return 0; }
ff9c5c23daea177437cf635a9bf9196ad1a970f9
[ "Markdown", "C" ]
11
C
zhangchuheng123/PAT
b9da180bd0589d5e819b88a4c5633a0c3c108a94
0721cde5a6cbce7d15dbd5b2c5e5d78de9678d86
refs/heads/master
<file_sep>import React, { useState, useEffect } from "react"; import Axios from "axios"; const ChatBox = props => { const [error, setError] = useState({ error: false }); const [msg, setMsg] = useState(""); const [msgCount, setMsgCount] = useState(0); const [selfData, setSelf] = useState(null); const [groupData, setGroupData] = useState(props.props.props.location.state); const { Socket } = props.Data; const submitMsg = E => { E.preventDefault(); var cssClass = "leftAlginChat"; var I = msgCount; I++; setMsgCount(I); if (I % 2 === 0) { cssClass = "RightAlginChat"; } EmitMsg({ From: `${selfData.Email}`, To: `${groupData.GroupId}`, Id: Socket.id, msg, msgCount: I, cssClass }); }; const EmitMsg = Data => { Socket.emit("Chat", Data); }; useEffect(() => { var Self; if ((selfData && groupData) === null) { Self = localStorage.getItem("user"); Self = JSON.parse(Self); setSelf(Self); } Socket.on(groupData.GroupId, data => { setMsgCount(data.msgCount); LiElement(data.msg, data.cssClass, data.From); }); }, []); const LiElement = (msg, liClass, Email) => { var node = document.createElement("LI"); var nodeEmail = document.createElement("P"); var nodeMsg = document.createElement("P"); nodeEmail.innerText = Email; nodeMsg.innerText = msg; node.appendChild(nodeMsg); node.appendChild(nodeEmail); if (liClass === "RightAlginChat") { nodeEmail.classList.add("msgEmailLeft"); } else { nodeEmail.classList.add("msgEmailRight"); } node.classList.add(liClass); document.getElementById("cl").appendChild(node); }; const deleteGroup = group => { const User = JSON.parse(localStorage.getItem("user")); const Data = { GroupId: group.GroupId, Email: User.Email }; Axios.defaults.headers = { Authorization: User.Token }; Axios.post("/group/user/remove", Data) .then(res => { if (res.data.error) { setError({ error: true, msg: res.data.msg }); return; } localStorage.removeItem("groups"); window.location = "/main"; }) .catch(err => { setError({ error: true, msg: "Some Error Exist" }); return; }); }; return ( <section className="chatWindow"> <div className=" cw_metaData"> {error.error === true ? ( <p className="alert alert-danger">{error.msg}</p> ) : null} <div className="heading"> {" "} <h4>{groupData.Name}</h4> </div> <div className="btn"> <button onClick={deleteGroup.bind(this, groupData)} className=" btn btn-danger" > <i style={{ display: "inline-block" }} className="fa fa-trash" aria-hidden="true" ></i> </button> </div> </div> <hr style={{ border: "1px solid black" }} /> <div className="chat-list"> <ul className="cl" id="cl"></ul> </div> <div className="msg-form"> <form onSubmit={submitMsg} className="form-group "> <input onChange={E => setMsg(E.target.value)} type="text" className="form-control mb-2" id="msg" /> <button type="submit" className="btn btn-primary"> Send </button> </form> </div> </section> ); }; export default ChatBox; <file_sep>module.exports = { Secret: "chatapp" }; <file_sep>const Router = require("express").Router(); const MysqlConn = require("../Config/DataBase.js"); const bcrypt = require("bcrypt"); const jwt = require("jsonwebtoken"); const Auth = require("../Config/Auth"); //@Route : "/user/login" //@Route-Type : POST //@Access : Public Router.post("/signup", (req, res) => { const { Name, Email, Password } = req.body; // Check If Email AllREADY Exist MysqlConn.query("SELECT Email FROM user", (err, Emails, fields) => { if (err) { res.status(400).json({ error: true, msg: "Some Technical Error" }); return; } var UserExist = false; Emails.map(value => { if (Email === value.Email) { UserExist = true; return; } }); if (UserExist) { res.status(200).json({ error: true, msg: "Email AllReady Exist" }); return; } //Insert New User bcrypt.genSalt(10, (err, salt) => { bcrypt.hash(Password, salt, (err, hash) => { if (err) { res.status(400).json({ error: true, msg: "Some Technical Error" }); return; } MysqlConn.query( `INSERT INTO user (Name,Email,Password) values('${Name}','${Email}','${hash}')`, (err, result, fields) => { if (err) { res.status(400).json({ error: true, msg: "Some DataBase Error" }); return; } res.status(200).json({ error: false, msg: "User Register Successfully" }); } ); }); }); }); }); //@Route : "/user/login" //@Route-Type : POST //@Access : Public Router.post("/login", (req, res) => { const { Email, Password } = req.body; MysqlConn.query( `SELECT * FROM user WHERE Email='${Email}'`, (err, result) => { if (err) { res.status(400).json({ error: true, msg: "Some Technical Error" }); return; } //IF USER EXIST if (result.length > 0) { //Check Password bcrypt.compare(Password, result[0].Password, (err, isSame) => { if (err) { res.status(400).json({ error: true, msg: "Some Technical Error" }); return; } //If Password is Correct if (isSame) { const Data = { Email: result[0].Email, Name: result[0].Name }; jwt.sign(Data, "chatapp", { expiresIn: 3600 * 2 }, (err, token) => { if (err) { res.status(400).json({ error: true, msg: "Some Technical Error" }); return; } res.status(200).json({ error: false, token: token, Email: result[0].Email, Name: result[0].Name }); }); return; } res.status(200).json({ error: true, msg: "Password Is Not Correct" }); }); return; } //IF USER NOT EXIST res.status(200).json({ error: true, msg: "User Not Exist" }); return; } ); }); //@Route : "/user/profile" //@Route-Type : POST //@Access : PRIVATE Router.post("/profile", Auth, (req, res) => { const token = req.headers.authorization; const user = jwt.decode(token); res.status(200).json({ error: false, user }); }); //@Route : "/user/token" //@Route-Type : GET //@Access : PRIVATE Router.get("/token", (req, res) => { const token = req.headers.authorization; jwt.verify(token, "chatapp", (err, decode) => { if (err) { res.status(200).json({ error: true, msg: "Token Expire", err }); return; } res.status(200).json({ error: false }); }); }); //@Route : "/user/group" //@Route-Type : POST //@Access : PRIVATE Router.post("/group", (req, res) => { const { Email } = req.body; MysqlConn.query( `SELECT * FROM chatgroup WHERE Created_By='${Email}'`, (err, result) => { if (err) { res.status(400).json({ error: true, msg: "Some Technical Error" }); return; } //IF GROUP NOT EXIST if (result.length <= 0) { res.status(200).json({ error: true, msg: "Group Not Exist" }); return; } res.status(200).json({ error: false, msg: "Success", result }); } ); }); module.exports = Router; <file_sep>import $ from "jquery"; const Width = $(window).width(); const Script = () => { const LGHeader = width => { if (width < 768) { if ($(".LgHeader").css("display") === "block") { $(".LgHeader").css({ display: "none" }); } } else { $(".LgHeader").css({ display: "inline-block" }); } }; //Tabs Toggle $(".tab-btn-1").bind("click", () => { const checkClass = $(".tab-btn-2").hasClass("active-tab"); if (checkClass) { $(".tab-btn-2").removeClass("active-tab"); $(".tab-btn-1").addClass("active-tab"); } }); $(".tab-btn-2").bind("click", () => { const checkClass = $(".tab-btn-1").hasClass("active-tab"); if (checkClass) { $(".tab-btn-1").removeClass("active-tab"); $(".tab-btn-2").addClass("active-tab"); } }); $(window).bind("resize", function() { const Width = $(window).width(); LGHeader(Width); }); //Default Calls LGHeader(Width); }; export default Script; <file_sep>const Router = require("express").Router(); const MysqlConn = require("../Config/DataBase.js"); const Auth = require("../Config/Auth"); //@Route : "/group/insert" //@Route-Type : POST //@Access : PRIVATE Router.post("/insert", Auth, (req, res) => { const { GroupName, GroupStatus, UniqueId, Created_By } = req.body; MysqlConn.query( `INSERT INTO chatgroup (Name,GroupId,Status,Created_By) values('${GroupName}','${UniqueId}','${GroupStatus}','${Created_By}')`, (err, result) => { if (err) { res.status(400).json({ error: true, msg: "Some Technical Error" }); return; } if (result.length <= 0) { res.status(200).json({ error: true, msg: "Some Error Found" }); return; } res.status(200).json({ error: false, msg: "Success" }); return; } ); }); //@Route : "/group/all" //@Route-Type : POST //@Access : PRIVATE Router.post("/all", Auth, (req, res) => { const { Email } = req.body; MysqlConn.query(`SELECT * FROM chatgroup`, (err, result) => { if (err) { res.status(400).json({ error: true, msg: "Some Technical Error" }); return; } if (result.length <= 0) { res.status(200).json({ error: true, msg: "Group Not Exist" }); return; } res.status(200).json({ error: false, msg: "Success", result }); }); }); //@Route : "/group/enroll" //@Route-Type : POST //@Access : PRIVATE Router.post("/enroll", (req, res) => { const { Email, GroupId } = req.body; MysqlConn.query( `SELECT * FROM enrollgroup WHERE Email='${Email}'`, (err, groups) => { if (err) { res.status(400).json({ error: true, msg: "Some Technical Error" }); return; } var isAlreadyExist = false; for (let index = 0; index < groups.length; index++) { const group = groups[index]; if (Email === group.Email && GroupId === group.GroupId) { isAlreadyExist = true; break; } } if (isAlreadyExist) { res.status(200).json({ error: true, msg: "Already Member" }); return; } // INSERT NEW GROUP MysqlConn.query( `INSERT INTO enrollgroup (Email,GroupId) values('${Email}','${GroupId}') `, (err, result) => { if (err) { res.status(400).json({ error: true, msg: "Some Technical Error" }); return; } res.status(200).json({ error: false, msg: "Success" }); } ); } ); }); //@Route : "/group/user/all" //@Route-Type : POST //@Access : PRIVATE Router.post("/user/all", (req, res) => { const Email = req.body.Email; MysqlConn.query( `SELECT chatgroup.GroupId,chatgroup.Name,chatgroup.Status, enrollgroup.GroupId,enrollgroup.Email FROM chatgroup INNER JOIN enrollgroup ON chatgroup.GroupId = enrollgroup.GroupId and enrollgroup.Email = '${Email}'`, (err, groups) => { if (err) { res.status(400).json({ error: true, msg: "Some Technical Error" }); return; } if (groups.length <= 0) { res.status(200).json({ error: true, msg: "Group Not Exist" }); return; } res.status(200).json({ error: false, msg: "Success", groups }); } ); }); //@Route : "/group/user/remove" //@Route-Type : POST //@Access : PRIVATE Router.post("/user/remove", (req, res) => { const { GroupId, Email } = req.body; MysqlConn.query( `DELETE FROM enrollgroup WHERE GroupId='${GroupId}' and Email='${Email}'`, (err, result) => { if (err) { res.status(400).json({ error: true, msg: "Some Technical Error" }); return; } res.status(200).json({ error: false, msg: "Success" }); } ); }); module.exports = Router; // SELECT enrollgroup.GroupId,chatgroup.GroupId,chatgroup.Name FROM chatgroup LEFT JOIN enrollgroup ON enrollgroup.Email = '<EMAIL>' and enrollgroup.GroupId <> chatgroup.GroupId; <file_sep>import React, { useState } from "react"; import { Link } from "react-router-dom"; import Axios from "axios"; const SignUp = () => { const [Email, setEmail] = useState(""); const [Name, setName] = useState(""); const [Password, setPassword] = useState("<PASSWORD>"); const [ConfirmPassword, setConfirmPassword] = useState("<PASSWORD>"); const [error, setError] = useState({ error: false }); const [success, setSuccess] = useState({ success: false }); const SubmitForm = E => { E.preventDefault(); if (Name === "" && Email === "") { setError({ error: true, msg: "Enter Correct Email And Name" }); return; } if (Password !== ConfirmPassword) { console.log(Password, ConfirmPassword); setError({ error: true, msg: "Password Not Match" }); return; } if (Password.length < 6) { setError({ error: true, msg: "Password Length To Short " }); return; } setError({ error: false }); const Data = { Name, Email, Password }; console.log(Data); Axios.post("/user/signup", Data) .then(res => { if (res.data.error) { setError({ error: true, msg: res.data.msg }); return; } setSuccess({ success: true, msg: res.data.msg }); }) .catch(err => { setError({ error: true, msg: err.response.data.msg }); }); }; return ( <section className="login"> <div className="heading"> <h2>Sign Up</h2> </div> <hr className="hr-black container" /> {/* If Any Error Exist */} {error.error === true ? ( <div className=" container "> <p className="alert-danger">{error.msg}</p> </div> ) : null} {/* On Success */} {success.success === true ? ( <div className=" container "> <p className="alert-success">{success.msg}</p> </div> ) : null} <form onSubmit={SubmitForm} className="container"> <div className="form-group"> <label htmlFor="name">Name</label> <input type="text" className="form-control" id="name" aria-describedby="name" placeholder="Enter Name" onChange={E => setName(E.currentTarget.value)} /> </div> <div className="form-group"> <label htmlFor="email">Email</label> <input type="email" className="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email" onChange={E => setEmail(E.currentTarget.value)} /> </div> <div className="form-group"> <label htmlFor="password">Password</label> <input type="<PASSWORD>" className="form-control" id="password" placeholder="<PASSWORD>" onChange={E => setPassword(E.currentTarget.value)} /> </div> <div className="form-group"> <label htmlFor="password">Confirm Password</label> <input type="<PASSWORD>" className="form-control" id="con-password" placeholder="<PASSWORD> Password" onChange={E => setConfirmPassword(E.currentTarget.value)} /> </div> <button type="submit" className="btn btn-primary"> Register </button> </form> <div className="links container"> <hr className="hr-black" /> <Link to="/" className="btn btn-primary"> Login </Link> </div> </section> ); }; export default SignUp; <file_sep>import React, { useState, useEffect } from "react"; import ChatMain from "../Chat/ChatMain"; import AllGroups from "../Group/AllGroups"; import Axios from "axios"; const Main = props => { const [Tab, setTab] = useState("ChatMain"); const ChangeTab = (E, T) => { if (E === "chattab") { setTab("ChatMain"); } else { setTab("AllGroups"); } }; useEffect(() => { const User = JSON.parse(localStorage.getItem("user")); Axios.defaults.headers = { Authorization: User.Token }; Axios.get("/user/token") .then(res => { if (res.data.error) { if (localStorage.getItem("user")) { localStorage.removeItem("user"); } if (localStorage.getItem("groups")) { localStorage.removeItem("groups"); } window.location = "/"; // console.log(res.data); return; } }) .catch(err => { if (localStorage.getItem("user")) { localStorage.removeItem("user"); } if (localStorage.getItem("groups")) { localStorage.removeItem("groups"); } window.location = "/"; }); }, []); return ( <main> <div className="row pm0"> <div className="col-sm-12 col-md-12 pm0"> <div className="row tab-btns pm0"> {/* Chat Tab BTN */} <div className="col-6 col-sm-6 col-md-6 brLeft tab-btn-1 active-tab pm0" onClick={ChangeTab.bind(this, "chattab")} > <span className="tab-btn">Chat</span> </div> {/* Friend Tab Btn */} <div className="col-6 col-sm-6 col-md-6 tab-btn-2 pm0 " onClick={ChangeTab.bind(this, "grouptab")} > <span className="tab-btn">Group</span> </div> </div> {/* Component */} <div style={{ marginTop: "17px" }}> {Tab === "ChatMain" ? ( <ChatMain props={props} /> ) : ( <AllGroups props={props} /> )} </div> </div> </div> </main> ); }; export default Main; <file_sep>import React from "react"; import { Link } from "react-router-dom"; import Logo from "../../Public/Img/logo.png"; const Header = () => { const Logout = E => { localStorage.removeItem("newGroupEvent"); localStorage.removeItem("user"); localStorage.removeItem("groups"); window.location = "/"; }; return ( <main> <div className="header row"> <div className="SmHeader col-sm-12 col-md-12 col-lg-12" style={{ paddingLeft: "8px" }} > <Link to="/"> <div className="headerMetaData" style={{ marginLeft: "0px", display: "inline-block" }} > <img style={{ display: "inline-block" }} src={Logo} alt="logo" /> </div> <div style={{ display: "inline-block", textAlign: "center", position: "absolute" }} > <h1 className="headerHeading">Chat App</h1> <p className="headerHeadLine">Make Connection</p> </div> </Link> <div className="headerBtn" style={{ float: "right" }} > {localStorage.getItem("user") === null ? null : ( <> <Link className="headerBTN" to="/main/user/profile"> <i className="fa fa-user" aria-hidden="true"></i> </Link> <button className="headerBTN" onClick={Logout.bind(this)} title="Logout" > <i className="fa fa-sign-out" aria-hidden="true"></i> </button> </> )} </div> </div> </div> </main> ); }; export default Header; <file_sep>import React, { useEffect, useState } from "react"; import { Link } from "react-router-dom"; import Logo from "../../Public/Img/logo.png"; import Axios from "axios"; const AllGroups = props => { const [error, setError] = useState({ error: false }); const [isLoading, setIsLoading] = useState(true); const [Groups, setGroups] = useState([]); useEffect(() => { const User = JSON.parse(localStorage.getItem("user")); Axios.defaults.headers = { Authorization: User.Token }; // const config = { // headers: { // "Content-Type": "multipart/form-data" // } // }; Axios.post("/group/all", { Email: User.Email }) .then(res => { if (res.data.error) { setIsLoading(false); setError({ error: true, msg: res.data.msg }); return; } setIsLoading(false); setGroups(res.data.result); }) .catch(err => { setIsLoading(false); setError({ error: true, msg: "Some Technical Error" }); }); }, []); const EnrollNow = Group => { localStorage.setItem("newGroupEvent", "true"); const user = JSON.parse(localStorage.getItem("user")); const Data = { Email: user.Email, GroupId: Group.GroupId }; Axios.defaults.headers = { Authorization: user.Token }; Axios.post("/group/enroll", Data) .then(res => { if (res.data.error) { setIsLoading(false); setError({ error: true, msg: res.data.msg }); return; } setIsLoading(false); window.location = "/"; }) .catch(err => { setIsLoading(false); setError({ error: true, msg: "Some Technical Error" }); }); }; const renderGroup = Groups => { return Groups.map((Group, i) => { return ( <div className="chatbox" key={i}> {/* cbl = Chat Box Left (Side) */} <div className="cbl"> <img src={Logo} alt="Profile" /> <div className="cb-heading"> <h5>{Group.Name}</h5> <p>{Group.Status}</p> </div> </div> <div className="cbr"> <button onClick={EnrollNow.bind(this, Group)}> <i className="fa fa-plus"></i> </button> </div> </div> ); }); }; return ( <section className="container chatmain"> {isLoading === true ? ( <p>isLoading</p> ) : ( <> {error.error === true ? ( <p style={{ padding: "80px" }} className="alert alert-danger"> {error.msg} </p> ) : ( <> {Groups.length <= 0 ? ( <p style={{ padding: "80px" }}>Group Not Exist</p> ) : ( renderGroup(Groups) )} </> )} </> )} <div className="ins_grp" style={{ marginBottom: "30px" }}> <Link to="/main/group/insert" className="btn btn-primary btn-block"> Create New Group </Link> </div> </section> ); }; export default AllGroups; <file_sep>import React, { useState } from "react"; import UniqueIdGen from "uniqid"; import Axios from "axios"; const Insert = props => { const [GroupName, setGroupName] = useState(null); const [GroupStatus, setGroupStatus] = useState(null); const [error, setError] = useState({ error: false }); const SubmitForm = E => { E.preventDefault(); const User = JSON.parse(localStorage.getItem("user")); const UniqueId = UniqueIdGen() + User.Email; if (!GroupName || !GroupStatus) { setError({ error: true, msg: "Enter Correct Group Details" }); return; } setError({ error: false }); const Data = { GroupName, GroupStatus, UniqueId, Created_By: User.Email }; Axios.defaults.headers = { Authorization: User.Token }; Axios.post("/group/insert", Data) .then(res => { if (res.data.error) { setError({ error: true, msg: res.data.msg }); return; } props.props.props.history.push("/main"); }) .catch(err => { setError({ error: true, msg: "Some Technical Error" }); }); }; return ( <section className="login"> <div className="heading"> <h2>Create Group</h2> </div> <hr className="hr-black container" /> {/* If Any Error Exist */} {error.error === true ? ( <div className=" container "> <p className="alert-danger">{error.msg}</p> </div> ) : null} <form onSubmit={SubmitForm} className="container"> <div className="form-group"> <label htmlFor="gpname">Group Name</label> <input type="text" className="form-control" id="gpname" placeholder="Group Name" onChange={E => setGroupName(E.target.value)} /> </div> <div className="form-group"> <label htmlFor="Status">Status</label> <input type="text" className="form-control" id="Status" placeholder="Status" onChange={E => setGroupStatus(E.target.value)} /> </div> <button type="submit" className="btn btn-primary"> Create </button> </form> </section> ); }; export default Insert; <file_sep>import Main from "./Main"; import ChatWindow from "../Chat/ChatBox"; import React, { Component } from "react"; import NotFound from "../Pages/NotFound"; import ConnectSocket from "../Socket/Socket"; import InsertGroup from "../Group/Insert"; import Profile from "../User/Profile"; export default class MainRoute extends Component { constructor(props) { super(props); this.state = { error: false }; } VerifyRoute(props) { var Location = props.location.pathname; var LocationLength = Location.length; if (Location.substr(LocationLength - 1, LocationLength) !== "/") { Location = Location.concat("/"); } if (Location === "/main/") { return { Component: Main, Data: null }; } else if (Location === "/main/chat/window/") { const User = JSON.parse(localStorage.getItem("user")); var Socket = ConnectSocket(User); return { Component: ChatWindow, Data: { Socket } }; } else if (Location === "/main/group/insert/") { return { Component: InsertGroup, Data: null }; } else if (Location === "/main/user/profile/") { return { Component: Profile, Data: null }; } else { return { Component: NotFound, Data: null }; } } render() { const Component = this.VerifyRoute(this.props.props); return ( <div> {<Component.Component Data={Component.Data} props={this.props} />} </div> ); } } <file_sep>const express = require("express"); const app = express(); const http = require("http").Server(app); const io = require("socket.io")(http); const session = require("express-session"); const sqlConn = require("./Config/DataBase"); const SocketEvent = require("./Socket/Socket.js"); const UserRoute = require("./Route/User.js"); const GroupRoute = require("./Route/Group"); const path = require("path"); //BODY PARSER const bodyParser = require("body-parser"); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // Express Session MiddleWare var sessionMiddleWare = session({ secret: "keyboard cat", resave: false, saveUninitialized: true, cookie: { secure: false, maxAge: 60000 } }); io.use((socket, next) => { sessionMiddleWare(socket.request, socket.request.res, next); }); // io.use(); app.use(sessionMiddleWare); //PORT const PORT = process.env.PORT || 7000; io.on("connection", socket => { var handshakeData = socket.handshake; // console.log(handshakeData); /*const OnlineUser = []; console.log(socket.handshake); if (socket.request.session.OnlineUser != undefined) { console.log(socket.request.session.OnlineUser); } else { console.log("ss"); socket.request.session.OnlineUser = [ { socketID: socket.id } ]; }*/ // OnlineUser = socket.session.OnlineUser; SocketEvent(socket, io); }); if (process.env.NODE_ENV === "production") { // SET STATIC FOLDER app.use(express.static("client/build")); app.get("*", (req, res) => { res.sendFile(path.resolve(__dirname, "client", "build", "index.html")); }); } //Set Route app.use("/user", UserRoute); app.use("/group", GroupRoute); //ENTRY POINT app.get("/", (req, res, next) => {}); http.listen(PORT, () => console.log("Server Run"));
0b6bc535d95a17f04704329b7022f4ee21be859a
[ "JavaScript" ]
12
JavaScript
ThePardeep/chat_app
6242c5ee6ebff435edf8702534afe4164530e156
1630dda790e2fdc457b3934d53b108608d4ccee0
refs/heads/master
<repo_name>JosephColby/MEDITECH---Drupal---Meditech.com<file_sep>/js/snazzymaps/snazzy.js google.maps.event.addDomListener(window, 'load', init); function init() { var mapOptions = { zoom: 15, center: new google.maps.LatLng(42.222403, -71.174153), styles: [{ "featureType": "landscape", "elementType": "labels", "stylers": [{ "visibility": "off" }] }, { "featureType": "transit", "elementType": "labels", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi", "elementType": "labels", "stylers": [{ "visibility": "off" }] }, { "featureType": "water", "elementType": "labels", "stylers": [{ "visibility": "off" }] }, { "featureType": "road", "elementType": "labels.icon", "stylers": [{ "visibility": "off" }] }, { "stylers": [{ "hue": "#00aaff" }, { "saturation": -100 }, { "gamma": 2.15 }, { "lightness": 12 }] }, { "featureType": "road", "elementType": "labels.text.fill", "stylers": [{ "visibility": "on" }, { "lightness": 24 }] }, { "featureType": "road", "elementType": "geometry", "stylers": [{ "lightness": 57 }] }], scrollwheel: false, navigationControl: false, mapTypeControl: false, scaleControl: false, disableDefaultUI: true, draggable: false, }; var mapElement = document.getElementById('map'); var map = new google.maps.Map(mapElement, mapOptions); }<file_sep>/js/main.js // Load Foundation $(document).foundation(); // Other Scripts and INITS $(document).ready(function () { // Sticky Navigation $(window).scroll(function () { console.log('scroll position: ' +$(window).scrollTop()); console.log('header container height: ' + $('#header-container').height()); if ($(window).scrollTop() >= $('#stickyheader').height()) $('#stickyheader').addClass('floating'); else $('#stickyheader').removeClass('floating'); }); // Load Sidebars $.slidebars(); // Closes Accordion $('.closeAccordion').click(function () { $('.accordion .content').removeClass('active'); }); });<file_sep>/js/stickynav/stickynav.js $(document).ready(function () { // Sticky Navigation $(window).scroll(function () { var navclass = '#nav'; // var navheight = $('#nav').outerHeight(); // console.log(navheight); if ($(window).scrollTop() >= 100) { console.log($(window).scrollTop()); $(navclass).addClass('js-sticky'); } else { $(navclass).removeClass('js-sticky'); } }); $(window).scroll(); // Search Bar Functionality var searchvisible = 0; // Check and see if the Search Box is open function closeSearch(obj) { if (searchvisible !== 0) { $(obj).slideUp(200); searchvisible = 0; } } $("a.search-menu").click(function (e) { // This stops the page scrolling to the top on a .search-menu link. e.preventDefault(); if (searchvisible === 0) { //Search is currently hidden. Slide down and show it. $("#js-searchbox").slideDown(200); $("#s").focus(); //Set focus on the search input field. searchvisible = 1; //Set search visible flag to visible. } else { //Search is currently showing. Slide it back up and hide it. closeSearch("#js-searchbox"); } }); // Close Search box if other menus are opened. $("a.main-menu, a.login-menu").click(function () { closeSearch("#js-searchbox"); }); });
acf01ea7352c6690fe5ab696790f70f56a5a05ef
[ "JavaScript" ]
3
JavaScript
JosephColby/MEDITECH---Drupal---Meditech.com
ee71709e28af4c9da0a027cf5c81f16c37da2e6b
a891a4413de348d25c5e0c77af7b3d07c21a95f4
refs/heads/master
<repo_name>AllenShen/ios-p2ptest<file_sep>/ios-p2ptest/Classes/p2pnetwork/P2PConnectManager.h // // Created by 沈冬冬 on 14-2-12. // // #ifndef __RakNetHandler_H_ #define __RakNetHandler_H_ #include <iostream> #include "RakNetStuff.h" #include "DS_Multilist.h" #include "P2PDefines.h" #include "NatTypeDetecteUPNPHandler.h" #include "NatPunchThroughHandler.h" #include "UDPProxyHandler.h" #include "cocos2d.h" USING_NS_CC; using namespace std; enum PeerConnectTypes { PeerConnectType_Node, PeerConnectType_p2p = 1, PeerConnectType_proxy }; class NatPunchThroughHandler; //和服务器相关的配置,网络断开之前,只需要初始化一次 struct GeneralData { NATTypeDetectionResult clientNatType; string selfInnerIpAddress; SystemAddress selfInnerAddress; /** * 服务对应的guid以及serveraddress */ SystemAddress NATCompleteServerAddress; //Nat complete server地址 包含类型检测 nat穿透 RakNetGUID punchServerGuid; //服务器的guid string natCompleteServerIp; unsigned short NatCompleteServetPort; string proxyServerIp; unsigned short proxyServerPort; SystemAddress ProxyServerArrress; //代理服务器地址 int averageServerLatency; //和服务器网络延时 GeneralData (): clientNatType(NAT_TYPE_UNKNOWN), selfInnerIpAddress(""), selfInnerAddress(), NATCompleteServerAddress(""), punchServerGuid(), averageServerLatency(-1) { } }; struct SelfPeerDataConfig { PeerConnectTypes connectType; //端端之间的连接类型 RakNetGUID peerGuid; //对方玩家的guid bool isHost; int averagePeerLatency; //平均的网络延迟时间 SelfPeerDataConfig(): peerGuid(0), isHost(false), connectType(PeerConnectType_Node), averagePeerLatency(0) { } }; class P2PConnectManager { private: P2PConnectManager(); public: NatTypeDetecteUPNPHandler * natTypeDetectionHandler; //nat类型检测client NatPunchThroughHandler* natPunchThroughHandler; //nat穿透服务类型检测 UDPProxyHandler* proxyHandler; vector<BaseStageHandler*> allHandler; private: void getIPAddress(); STATIC_GET_SINGLEINSTANCE(P2PConnectManager); public: GeneralData* generalConfigData; //通用的配置数据 SelfPeerDataConfig* selfPeerDataConfig; //peer的配置数据 P2PConnectStages curConnectStage; int latencyCheckIndex; TimeMS nextActionTime; public: void initInfo(); void enterStage(P2PConnectStages stage,Packet * packet = NULL); void startNetWork(); void UpdateRakNet(); void onConnectSuccess(PeerConnectTypes connectType); //连接成功的回调函数 void onConnectFailed(); //连接失败的回调 virtual ~P2PConnectManager(); }; #endif //__RakNetHandler_H_ <file_sep>/ios-p2ptest/Classes/p2pnetwork/P2PManagerFunc.cpp // // Created by 沈冬冬 on 14-2-20. // // #include "P2PManagerFunc.h" #include "RakString.h" #include "P2PDefines.h" #include "MessageIdentifiers.h" #include "P2PConnectManager.h" P2PManagerFunc::P2PManagerFunc() { } void P2PManagerFunc::printPacketMessages(Packet *packet) { if(packet == NULL) return; int packetCode = packet->data[0]; const char* targetName; if (strcmp(packet->systemAddress.ToString(false),P2PConnectManager::getInstance()->generalConfigData->natCompleteServerIp.c_str())==0) { targetName = "NATPunchthroughServer"; } else { targetName = packet->systemAddress.ToString(true); } switch (packetCode) { case ID_CONNECTION_ATTEMPT_FAILED: printf("连接 to %s 失败 \n",targetName); break; case ID_IP_RECENTLY_CONNECTED: printf("This IP address recently connected from %s\n",targetName); break; case ID_INCOMPATIBLE_PROTOCOL_VERSION: printf("Incompatible protocol version from %s\n",targetName); break; case ID_NO_FREE_INCOMING_CONNECTIONS: printf("No free incoming connections to %s\n",targetName); break; case ID_DISCONNECTION_NOTIFICATION: printf("Disconnected from %s \n",targetName); break; case ID_CONNECTION_LOST: printf("connection to %s 断开 \n",targetName); break; } } P2PManagerFunc::~P2PManagerFunc() { }<file_sep>/ios-p2ptest/Classes/ReplicaManager3Irrlicht.cpp // // Created by 沈冬冬 on 14-2-12. // // #include "ReplicaManager3Irrlicht.h" #include "BaseIrrlichtReplica.h" #include "PlayerReplica.h" ReplicaManager3Irrlicht::ReplicaManager3Irrlicht() { } ReplicaManager3Irrlicht::~ReplicaManager3Irrlicht() { } RakNet::Replica3 *Connection_RM3Irrlicht::AllocReplica(RakNet::BitStream *allocationId, ReplicaManager3 *replicaManager3) { RakNet::RakString typeName; allocationId->Read(typeName); if (typeName=="PlayerReplica") { BaseIrrlichtReplica *r = new PlayerReplica; r->demo=demo; return r; } // if (typeName=="BallReplica") // { // BaseIrrlichtReplica *r = new BallReplica; // r->demo=demo; // return r; // } return 0; } Connection_RM3 *ReplicaManager3Irrlicht::AllocConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID) const { return new Connection_RM3Irrlicht(systemAddress,rakNetGUID,this->demo); } void ReplicaManager3Irrlicht::DeallocConnection(Connection_RM3 *connection) const { delete connection; } <file_sep>/ios-p2ptest/Classes/RakNetStuff.h // // Created by 沈冬冬 on 14-2-12. // // #ifndef __RakNetStuff_H_ #define __RakNetStuff_H_ #include <iostream> #include "RakPeerInterface.h" #include "ReplicaManager3.h" #include "NatPunchthroughClient.h" #include "CloudClient.h" #include "FullyConnectedMesh2.h" #include "UDPProxyClient.h" #include "TCPInterface.h" #include "HTTPConnection.h" #include "MessageIdentifiers.h" #include "ReplicaManager3Irrlicht.h" #include "NatTypeDetectionClient.h" #include "P2PDefines.h" using namespace RakNet; class PlayerReplica; class RakNetStuff { private: void initRakPeer(); void init(); public: static RakPeerInterface *rakPeer; static PlayerReplica *playerReplica; // Network object that represents the player static NetworkIDManager *networkIDManager; // Unique IDs per network object static ReplicaManager3Irrlicht *replicaManager3; // Autoreplicate network objects static CloudClient *cloudClient; // Used to upload game instance to the cloud RakNetStuff(); void clearInfo(); STATIC_GET_SINGLEINSTANCE(RakNetStuff); virtual ~RakNetStuff(); }; #endif //__RakNetStuff_H_ <file_sep>/ios-p2ptest/Classes/raknet/PlayerReplica.cpp // // Created by 沈冬冬 on 14-2-12. // // #include "PlayerReplica.h" #include "GetTime.h" #include "RakNetStuff.h" DataStructures::List<PlayerReplica*> PlayerReplica::playerList; PlayerReplica::PlayerReplica() { // model=0; rotationDeltaPerMS=0.0f; isMoving=false; deathTimeout=0; lastUpdate=RakNet::GetTimeMS(); playerList.Push(this,_FILE_AND_LINE_); } PlayerReplica::~PlayerReplica() { unsigned int index = playerList.GetIndexOf(this); if (index != (unsigned int) -1) playerList.RemoveAtIndexFast(index); } void PlayerReplica::WriteAllocationID(RakNet::Connection_RM3 *destinationConnection, RakNet::BitStream *allocationIdBitstream) const { allocationIdBitstream->Write(RakNet::RakString("PlayerReplica")); } void PlayerReplica::SerializeConstruction(RakNet::BitStream *constructionBitstream, RakNet::Connection_RM3 *destinationConnection) { BaseIrrlichtReplica::SerializeConstruction(constructionBitstream, destinationConnection); constructionBitstream->Write(rotationAroundYAxis); constructionBitstream->Write(playerName); constructionBitstream->Write(IsDead()); } bool PlayerReplica::DeserializeConstruction(RakNet::BitStream *constructionBitstream, RakNet::Connection_RM3 *sourceConnection) { if (!BaseIrrlichtReplica::DeserializeConstruction(constructionBitstream, sourceConnection)) return false; constructionBitstream->Read(rotationAroundYAxis); constructionBitstream->Read(playerName); constructionBitstream->Read(isDead); return true; } void PlayerReplica::PostDeserializeConstruction(RakNet::BitStream *constructionBitstream, RakNet::Connection_RM3 *destinationConnection) { // Object was remotely created and all data loaded. Now we can make the object visible // scene::IAnimatedMesh* mesh = 0; // scene::ISceneManager *sm = demo->GetSceneManager(); // mesh = sm->getMesh(IRRLICHT_MEDIA_PATH "sydney.md2"); // model = sm->addAnimatedMeshSceneNode(mesh, 0); // // model->setPosition(position); // model->setRotation(core::vector3df(0, rotationAroundYAxis, 0)); // model->setScale(core::vector3df(2,2,2)); // model->setMD2Animation(scene::EMAT_STAND); // curAnim=scene::EMAT_STAND; // model->setMaterialTexture(0, demo->GetDevice()->getVideoDriver()->getTexture(IRRLICHT_MEDIA_PATH "sydney.bmp")); // model->setMaterialFlag(video::EMF_LIGHTING, true); // model->addShadowVolumeSceneNode(); // model->setAutomaticCulling ( scene::EAC_BOX ); // model->setVisible(true); // model->setAnimationEndCallback(this); // wchar_t playerNameWChar[1024]; // mbstowcs(playerNameWChar, playerName.C_String(), 1024); // scene::IBillboardSceneNode *bb = sm->addBillboardTextSceneNode(0, playerNameWChar, model); // bb->setSize(core::dimension2df(40,20)); // bb->setPosition(core::vector3df(0,model->getBoundingBox().MaxEdge.Y+bb->getBoundingBox().MaxEdge.Y-bb->getBoundingBox().MinEdge.Y+5.0,0)); // bb->setColor(video::SColor(255,255,128,128), video::SColor(255,255,128,128)); } void PlayerReplica::PreDestruction(RakNet::Connection_RM3 *sourceConnection) { // if (model) // model->remove(); } RM3SerializationResult PlayerReplica::Serialize(RakNet::SerializeParameters *serializeParameters) { BaseIrrlichtReplica::Serialize(serializeParameters); // serializeParameters->outputBitstream[0].Write(position); serializeParameters->outputBitstream[0].Write(rotationAroundYAxis); serializeParameters->outputBitstream[0].Write(isMoving); serializeParameters->outputBitstream[0].Write(IsDead()); return RM3SR_BROADCAST_IDENTICALLY; } void PlayerReplica::Deserialize(RakNet::DeserializeParameters *deserializeParameters) { BaseIrrlichtReplica::Deserialize(deserializeParameters); // deserializeParameters->serializationBitstream[0].Read(position); deserializeParameters->serializationBitstream[0].Read(rotationAroundYAxis); deserializeParameters->serializationBitstream[0].Read(isMoving); bool wasDead=isDead; deserializeParameters->serializationBitstream[0].Read(isDead); if (isDead==true && wasDead==false) { // demo->PlayDeathSound(position); } // core::vector3df positionOffset; // positionOffset=position-model->getPosition(); // positionDeltaPerMS = positionOffset / INTERP_TIME_MS; // float rotationOffset; // rotationOffset=GetRotationDifference(rotationAroundYAxis,model->getRotation().Y); // rotationDeltaPerMS = rotationOffset / INTERP_TIME_MS; // interpEndTime = RakNet::GetTimeMS() + (RakNet::TimeMS) INTERP_TIME_MS; } void PlayerReplica::Update(RakNet::TimeMS curTime) { // Is a locally created object? if (creatingSystemGUID==RakNetStuff::rakPeer->GetGuidFromSystemAddress(RakNet::UNASSIGNED_SYSTEM_ADDRESS)) { // Local player has no mesh to interpolate // Input our camera position as our player position // RakNetStuff::playerReplica->position=demo->GetSceneManager()->getActiveCamera()->getPosition()-irr::core::vector3df(0,CAMERA_HEIGHT,0); // RakNetStuff::playerReplica->rotationAroundYAxis=demo->GetSceneManager()->getActiveCamera()->getRotation().Y-90.0f; // isMoving=demo->IsMovementKeyDown(); return; } // Update interpolation RakNet::TimeMS elapsed = curTime-lastUpdate; if (elapsed<=1) return; if (elapsed>100) elapsed=100; lastUpdate=curTime; // irr::core::vector3df curPositionDelta = position-model->getPosition(); // irr::core::vector3df interpThisTick = positionDeltaPerMS*(float) elapsed; // if (curTime < interpEndTime && interpThisTick.getLengthSQ() < curPositionDelta.getLengthSQ()) // { // model->setPosition(model->getPosition()+positionDeltaPerMS*(float) elapsed); // } // else // { // model->setPosition(position); // } // // float curRotationDelta = GetRotationDifference(rotationAroundYAxis,model->getRotation().Y); // float interpThisTickRotation = rotationDeltaPerMS*(float)elapsed; // if (curTime < interpEndTime && fabs(interpThisTickRotation) < fabs(curRotationDelta)) // { // model->setRotation(model->getRotation()+core::vector3df(0,interpThisTickRotation,0)); // } // else // { // model->setRotation(core::vector3df(0,rotationAroundYAxis,0)); // } // // if (isDead) // { // UpdateAnimation(scene::EMAT_DEATH_FALLBACK); // model->setLoopMode(false); // } // else if (curAnim!=scene::EMAT_ATTACK) // { // if (isMoving) // { // UpdateAnimation(scene::EMAT_RUN); // model->setLoopMode(true); // } // else // { // UpdateAnimation(scene::EMAT_STAND); // model->setLoopMode(true); // } // } } //void PlayerReplica::UpdateAnimation(irr::scene::EMD2_ANIMATION_TYPE anim) //{ // if (anim!=curAnim) // model->setMD2Animation(anim); // curAnim=anim; //} float PlayerReplica::GetRotationDifference(float r1, float r2) { float diff = r1-r2; while (diff>180.0f) diff-=360.0f; while (diff<-180.0f) diff+=360.0f; return diff; } //void PlayerReplica::OnAnimationEnd(scene::IAnimatedMeshSceneNode* node) //{ // if (curAnim==scene::EMAT_ATTACK) // { // if (isMoving) // { // UpdateAnimation(scene::EMAT_RUN); // model->setLoopMode(true); // } // else // { // UpdateAnimation(scene::EMAT_STAND); // model->setLoopMode(true); // } // } //} void PlayerReplica::PlayAttackAnimation(void) { if (isDead==false) { // UpdateAnimation(scene::EMAT_ATTACK); // model->setLoopMode(false); } } bool PlayerReplica::IsDead(void) const { return deathTimeout > RakNet::GetTimeMS(); } <file_sep>/ios-p2ptest/Classes/p2pnetwork/NatPunchThroughHandler.h // // Created by 沈冬冬 on 14-2-20. // // #ifndef __NatPunchThroughHandler_H_ #define __NatPunchThroughHandler_H_ #include <iostream> #include "BaseStageHandler.h" #include "NatPunchthroughClient.h" #include "P2PConnectManager.h" class NatPunchThroughHandler : public BaseStageHandler,public NatPunchthroughDebugInterface{ public: NatPunchthroughClient* punchthroughClient; NatPunchThroughHandler(); void startPunch(RakNetGUID& guid); virtual ~NatPunchThroughHandler(); virtual void startCountDown() override; virtual void onTimeOutHandler() override; virtual void OnClientMessage(const char *msg) override; }; #endif //__NatPunchThroughHandler_H_ <file_sep>/ios-p2ptest/Classes/RakNetStuff.cpp // // Created by 沈冬冬 on 14-2-12. // // #include "RakNetStuff.h" #include "NetworkIDManager.h" #include "PlayerReplica.h" #include "NatTypeDetectionClient.h" #include "P2PConnectManager.h" RakPeerInterface* RakNetStuff::rakPeer = NULL; PlayerReplica* RakNetStuff::playerReplica = NULL; NetworkIDManager* RakNetStuff::networkIDManager = NULL; ReplicaManager3Irrlicht* RakNetStuff::replicaManager3 = NULL; CloudClient* RakNetStuff::cloudClient = NULL; RakNetStuff::RakNetStuff() { this->initRakPeer(); this->init(); } void RakNetStuff::clearInfo() { if(rakPeer == NULL) return; if(RakNetStuff::replicaManager3) rakPeer->DetachPlugin(RakNetStuff::replicaManager3); if(RakNetStuff::cloudClient) rakPeer->DetachPlugin(RakNetStuff::cloudClient); RakPeerInterface::DestroyInstance(rakPeer); rakPeer = NULL; } void RakNetStuff::initRakPeer() { static const int MAX_PLAYERS=32; rakPeer=RakNet::RakPeerInterface::GetInstance(); RakNet::SocketDescriptor sd(1234,0); sd.socketFamily=AF_INET; // Only IPV4 supports broadcast on 255.255.255.255 while (IRNS2_Berkley::IsPortInUse(sd.port, sd.hostAddress, sd.socketFamily, SOCK_DGRAM)==true) sd.port++; RakNet::StartupResult sr = rakPeer->Startup(MAX_PLAYERS+1,&sd,1); RakAssert(sr==RakNet::RAKNET_STARTED); rakPeer->SetMaximumIncomingConnections(MAX_PLAYERS); // Fast disconnect for easier testing of host migration rakPeer->SetTimeoutTime(5000,UNASSIGNED_SYSTEM_ADDRESS); // ReplicaManager3 replies on NetworkIDManager. It assigns numbers to objects so they can be looked up over the network // It's a class in case you wanted to have multiple worlds, then you could have multiple instances of NetworkIDManager } void RakNetStuff::init() { static const unsigned short TCP_PORT=0; static const RakNet::TimeMS UDP_SLEEP_TIMER=30; networkIDManager=new NetworkIDManager; // Automatically sends around new / deleted / changed game objects replicaManager3 = new ReplicaManager3Irrlicht; replicaManager3->SetNetworkIDManager(networkIDManager); rakPeer->AttachPlugin(replicaManager3); // Automatically destroy connections, but don't create them so we have more control over when a system is considered ready to play replicaManager3->SetAutoManageConnections(false,true); // Create and register the network object that represents the player playerReplica = new PlayerReplica; replicaManager3->Reference(playerReplica); // Uploads game instance, basically client half of a directory server // Server code is in NATCompleteServer sample cloudClient=new CloudClient; rakPeer->AttachPlugin(cloudClient); //连接到公共的穿墙服务器 ConnectionAttemptResult car = rakPeer->Connect(P2PConnectManager::getInstance()->generalConfigData->natCompleteServerIp.c_str(), P2PConnectManager::getInstance()->generalConfigData->NatCompleteServetPort,0,0); // ConnectionAttemptResult car = rakPeer->Connect("172.26.192.159", DEFAULT_NAT_PUNCHTHROUGH_FACILITATOR_PORT,0,0); RakAssert(car==CONNECTION_ATTEMPT_STARTED); // Advertise ourselves on the lAN if the NAT punchthrough server is not available //for (int i=0; i < 8; i++) // rakPeer->AdvertiseSystem("255.255.255.255", 1234+i, 0,0,0); } RakNetStuff::~RakNetStuff() { }<file_sep>/ios-p2ptest/Classes/p2pnetwork/UDPProxyHandler.h // // Created by 沈冬冬 on 14-2-21. // // #ifndef __UDPProxyHandler_H_ #define __UDPProxyHandler_H_ #include <iostream> #include "BaseStageHandler.h" #include "UDPProxyClient.h" class UDPProxyHandler :public BaseStageHandler,public UDPProxyClientResultHandler{ public: UDPProxyClient* proxyClient; UDPProxyHandler(); void startConnectToProxyServer(); virtual void OnForwardingSuccess(const char *proxyIPAddress, unsigned short proxyPort, SystemAddress proxyCoordinator, SystemAddress sourceAddress, SystemAddress targetAddress, RakNetGUID targetGuid, RakNet::UDPProxyClient *proxyClientPlugin); virtual void OnForwardingNotification(const char *proxyIPAddress, unsigned short proxyPort, SystemAddress proxyCoordinator, SystemAddress sourceAddress, SystemAddress targetAddress, RakNetGUID targetGuid, RakNet::UDPProxyClient *proxyClientPlugin); virtual void OnNoServersOnline(SystemAddress proxyCoordinator, SystemAddress sourceAddress, SystemAddress targetAddress, RakNetGUID targetGuid, RakNet::UDPProxyClient *proxyClientPlugin); virtual void OnRecipientNotConnected(SystemAddress proxyCoordinator, SystemAddress sourceAddress, SystemAddress targetAddress, RakNetGUID targetGuid, RakNet::UDPProxyClient *proxyClientPlugin); virtual void OnAllServersBusy(SystemAddress proxyCoordinator, SystemAddress sourceAddress, SystemAddress targetAddress, RakNetGUID targetGuid, RakNet::UDPProxyClient *proxyClientPlugin); virtual void OnForwardingInProgress(const char *proxyIPAddress, unsigned short proxyPort, SystemAddress proxyCoordinator, SystemAddress sourceAddress, SystemAddress targetAddress, RakNetGUID targetGuid, RakNet::UDPProxyClient *proxyClientPlugin); virtual ~UDPProxyHandler(); virtual void startCountDown() override; virtual void onTimeOutHandler() override; }; #endif //__UDPProxyHandler_H_ <file_sep>/ios-p2ptest/Classes/raknet/PlayerReplica.h // // Created by 沈冬冬 on 14-2-12. // // #ifndef __PlayerReplica_H_ #define __PlayerReplica_H_ #include "Rand.h" #include "ReplicaManager3.h" #include "BaseIrrlichtReplica.h" using namespace RakNet; class CDemo; class PlayerReplica : public BaseIrrlichtReplica{ public: PlayerReplica(); virtual ~PlayerReplica(); // Every function below, before Update overriding a function in Replica3 virtual void WriteAllocationID(RakNet::Connection_RM3 *destinationConnection, RakNet::BitStream *allocationIdBitstream) const; virtual void SerializeConstruction(RakNet::BitStream *constructionBitstream, RakNet::Connection_RM3 *destinationConnection); virtual bool DeserializeConstruction(RakNet::BitStream *constructionBitstream, RakNet::Connection_RM3 *sourceConnection); virtual RakNet::RM3SerializationResult Serialize(RakNet::SerializeParameters *serializeParameters); virtual void Deserialize(RakNet::DeserializeParameters *deserializeParameters); virtual void PostDeserializeConstruction(RakNet::BitStream *constructionBitstream, RakNet::Connection_RM3 *destinationConnection); virtual void PreDestruction(RakNet::Connection_RM3 *sourceConnection); virtual void Update(RakNet::TimeMS curTime); // void UpdateAnimation(irr::scene::EMD2_ANIMATION_TYPE anim); float GetRotationDifference(float r1, float r2); // virtual void OnAnimationEnd(irr::scene::IAnimatedMeshSceneNode* node); void PlayAttackAnimation(void); // playerName is only sent in SerializeConstruction, since it doesn't change RakNet::RakString playerName; // Networked rotation float rotationAroundYAxis; // Interpolation variables, not networked // irr::core::vector3df positionDeltaPerMS; float rotationDeltaPerMS; RakNet::TimeMS interpEndTime, lastUpdate; // Updated based on the keypresses, to control remote animation bool isMoving; // Only instantiated for remote systems, you never see yourself // irr::scene::IAnimatedMeshSceneNode* model; // irr::scene::EMD2_ANIMATION_TYPE curAnim; // deathTimeout is set from the local player RakNet::TimeMS deathTimeout; bool IsDead(void) const; // isDead is set from network packets for remote players bool isDead; // List of all players, including our own static DataStructures::List<PlayerReplica*> playerList; }; #endif //__PlayerReplica_H_ <file_sep>/ios-p2ptest/Classes/BaseIrrlichtReplica.h // // Created by 沈冬冬 on 14-2-12. // // #ifndef __BaseIrrlichtReplica_H_ #define __BaseIrrlichtReplica_H_ #include <iostream> #include "RakNetTime.h" #include "ReplicaManager3.h" using namespace RakNet; class CDemo; class BaseIrrlichtReplica : public RakNet::Replica3 { public: BaseIrrlichtReplica(); virtual ~BaseIrrlichtReplica(); virtual RakNet::RM3ConstructionState QueryConstruction(RakNet::Connection_RM3 *destinationConnection, RakNet::ReplicaManager3 *replicaManager3) {return QueryConstruction_PeerToPeer(destinationConnection);} virtual bool QueryRemoteConstruction(RakNet::Connection_RM3 *sourceConnection) {return QueryRemoteConstruction_PeerToPeer(sourceConnection);} virtual void DeallocReplica(RakNet::Connection_RM3 *sourceConnection) {delete this;} virtual RakNet::RM3QuerySerializationResult QuerySerialization(RakNet::Connection_RM3 *destinationConnection) {return QuerySerialization_PeerToPeer(destinationConnection);} virtual void SerializeConstruction(RakNet::BitStream *constructionBitstream, RakNet::Connection_RM3 *destinationConnection); virtual bool DeserializeConstruction(RakNet::BitStream *constructionBitstream, RakNet::Connection_RM3 *sourceConnection); virtual RakNet::RM3SerializationResult Serialize(RakNet::SerializeParameters *serializeParameters); virtual void Deserialize(RakNet::DeserializeParameters *deserializeParameters); virtual void SerializeDestruction(RakNet::BitStream *destructionBitstream, RakNet::Connection_RM3 *destinationConnection) {} virtual bool DeserializeDestruction(RakNet::BitStream *destructionBitstream, RakNet::Connection_RM3 *sourceConnection) {return true;} virtual RakNet::RM3ActionOnPopConnection QueryActionOnPopConnection(RakNet::Connection_RM3 *droppedConnection) const {return QueryActionOnPopConnection_PeerToPeer(droppedConnection);} /// This function is not derived from Replica3, it's specific to this app /// Called from CDemo::UpdateRakNet virtual void Update(RakNet::TimeMS curTime); // Set when the object is constructed CDemo *demo; // real is written on the owner peer, read on the remote peer // irr::core::vector3df position; RakNet::TimeMS creationTime; }; #endif //__BaseIrrlichtReplica_H_ <file_sep>/ios-p2ptest/Classes/p2pnetwork/NatPunchThroughHandler.cpp // // Created by 沈冬冬 on 14-2-20. // // #include "NatPunchThroughHandler.h" #include "NatPunchthroughClient.h" #include "GetTime.h" NatPunchThroughHandler::NatPunchThroughHandler(): punchthroughClient(NULL) { punchthroughClient = new NatPunchthroughClient(); punchthroughClient->SetDebugInterface(this); RakNetStuff::getInstance()->rakPeer->AttachPlugin(punchthroughClient); } void NatPunchThroughHandler::startPunch(RakNetGUID& guid) { punchthroughClient->OpenNAT(guid, P2PConnectManager::getInstance()->generalConfigData->NATCompleteServerAddress); } void NatPunchThroughHandler::startCountDown() { BaseStageHandler::startCountDown(); this->timeMileStone = GetTimeMS() + 100000; } void NatPunchThroughHandler::onTimeOutHandler() { if(!this->isOnTimeCountingDown || this->isTimeUp) return; BaseStageHandler::onTimeOutHandler(); printf("Nat 穿墙执行超时 \n"); } NatPunchThroughHandler::~NatPunchThroughHandler() { } void NatPunchThroughHandler::OnClientMessage(const char *msg) { printf("---------------- debug info: "); printf(msg); printf("\n"); } <file_sep>/ios-p2ptest/Classes/p2pnetwork/UDPProxyHandler.cpp // // Created by 沈冬冬 on 14-2-21. // // #include "UDPProxyHandler.h" #include "RakNetStuff.h" #include "P2PConnectManager.h" #include "GetTime.h" #include "UDPProxyCommon.h" UDPProxyHandler::UDPProxyHandler(): proxyClient(NULL) { proxyClient = new UDPProxyClient(); RakNetStuff::getInstance()->rakPeer->AttachPlugin(proxyClient); proxyClient->SetResultHandler(this); } UDPProxyHandler::~UDPProxyHandler() { } void UDPProxyHandler::startCountDown() { BaseStageHandler::startCountDown(); this->timeMileStone = GetTimeMS() + 4000; } void UDPProxyHandler::onTimeOutHandler() { if(!this->isOnTimeCountingDown || this->isTimeUp) return; BaseStageHandler::onTimeOutHandler(); printf("连接代理服务器超时。。。。。。。 \n"); P2PConnectManager::getInstance()->onConnectFailed(); } void UDPProxyHandler::startConnectToProxyServer() { this->startCountDown(); RakNet::ConnectionAttemptResult car = RakNetStuff::rakPeer->Connect(P2PConnectManager::getInstance()->generalConfigData->proxyServerIp.c_str(), P2PConnectManager::getInstance()->generalConfigData->proxyServerPort,0,0, NULL,0,12,500,4000); if(car == INVALID_PARAMETER || car == CANNOT_RESOLVE_DOMAIN_NAME || car == SECURITY_INITIALIZATION_FAILED) { printf("--------------- connect to punch server error -----------------\n"); } } void UDPProxyHandler::OnForwardingSuccess(const char *proxyIPAddress, unsigned short proxyPort, SystemAddress proxyCoordinator, SystemAddress sourceAddress, SystemAddress targetAddress, RakNetGUID targetGuid, RakNet::UDPProxyClient *proxyClientPlugin) { if(this->isTimeUp) return; printf("Datagrams forwarded by proxy %s:%i to target %s.\n", proxyIPAddress, proxyPort, targetAddress.ToString(false)); printf("Connecting to proxy, which will be received by target.\n"); // proxyIPAddress = DEFAULT_SERVER_ADDRESS; // timeout=RakNet::GetTimeMS() + 500000; char portInfo[30] = {0}; sprintf(portInfo, "%d",proxyPort); P2PConnectManager::getInstance()->enterStage(P2PStage_ConnectProxyServer); //转发成功 连接至代理服务器 ConnectionAttemptResult car = proxyClientPlugin->GetRakPeerInterface()->Connect(proxyIPAddress, proxyPort, 0, 0); RakAssert(car==CONNECTION_ATTEMPT_STARTED); // sampleResult=SUCCEEDED; } void UDPProxyHandler::OnForwardingNotification(const char *proxyIPAddress, unsigned short proxyPort, SystemAddress proxyCoordinator, SystemAddress sourceAddress, SystemAddress targetAddress, RakNetGUID targetGuid, RakNet::UDPProxyClient *proxyClientPlugin) { if(this->isTimeUp) return; printf("Source %s has setup forwarding to us through proxy %s:%i.\n", sourceAddress.ToString(false), proxyIPAddress, proxyPort); P2PConnectManager::getInstance()->enterStage(P2PStage_ConnectProxyServer); } void UDPProxyHandler::OnNoServersOnline(SystemAddress proxyCoordinator, SystemAddress sourceAddress, SystemAddress targetAddress, RakNetGUID targetGuid, RakNet::UDPProxyClient *proxyClientPlugin) { printf("Failure: No servers logged into coordinator.\n"); P2PConnectManager::getInstance()->onConnectFailed(); } void UDPProxyHandler::OnRecipientNotConnected(SystemAddress proxyCoordinator, SystemAddress sourceAddress, SystemAddress targetAddress, RakNetGUID targetGuid, RakNet::UDPProxyClient *proxyClientPlugin) { printf("Failure: Recipient not connected to coordinator.\n"); P2PConnectManager::getInstance()->onConnectFailed(); } void UDPProxyHandler::OnAllServersBusy(SystemAddress proxyCoordinator, SystemAddress sourceAddress, SystemAddress targetAddress, RakNetGUID targetGuid, RakNet::UDPProxyClient *proxyClientPlugin) { printf("Failure: No servers have available forwarding ports.\n"); P2PConnectManager::getInstance()->onConnectFailed(); } void UDPProxyHandler::OnForwardingInProgress(const char *proxyIPAddress, unsigned short proxyPort, SystemAddress proxyCoordinator, SystemAddress sourceAddress, SystemAddress targetAddress, RakNetGUID targetGuid, RakNet::UDPProxyClient *proxyClientPlugin) { printf("Notification: Forwarding already in progress.\n"); P2PConnectManager::getInstance()->onConnectFailed(); }<file_sep>/ios-p2ptest/Classes/p2pnetwork/P2PConnectManager.cpp // // Created by 沈冬冬 on 14-2-12. // // #include <ifaddrs.h> #include "P2PConnectManager.h" #include "GetTime.h" #include "NatTypeDetecteUPNPHandler.h" #include "P2PManagerFunc.h" #include "UDPProxyCommon.h" #include "HelloWorldScene.h" P2PConnectManager::P2PConnectManager(): natTypeDetectionHandler(NULL), natPunchThroughHandler(NULL), proxyHandler(NULL), latencyCheckIndex(0), generalConfigData(NULL), nextActionTime(0) { } void P2PConnectManager::initInfo() { this->generalConfigData = new GeneralData(); this->selfPeerDataConfig = new SelfPeerDataConfig(); generalConfigData->clientNatType = NAT_TYPE_UNKNOWN; generalConfigData->natCompleteServerIp = DEFAULT_NAT_PUNCHTHROUGH_FACILITATOR_IP; this->generalConfigData->NatCompleteServetPort = DEFAULT_NAT_PUNCHTHROUGH_FACILITATOR_PORT; this->generalConfigData->proxyServerIp = DEFAULT_UDPPROXY_IP; this->generalConfigData->proxyServerPort = DEFAULT_UDPPROXY_PORT; generalConfigData->NATCompleteServerAddress = SystemAddress(generalConfigData->natCompleteServerIp.c_str(),generalConfigData->NatCompleteServetPort); generalConfigData->ProxyServerArrress = SystemAddress(generalConfigData->proxyServerIp.c_str(),generalConfigData->proxyServerPort); natTypeDetectionHandler = new NatTypeDetecteUPNPHandler(); natPunchThroughHandler = new NatPunchThroughHandler(); proxyHandler = new UDPProxyHandler(); allHandler.push_back(natTypeDetectionHandler); allHandler.push_back(natPunchThroughHandler); allHandler.push_back(proxyHandler); this->selfPeerDataConfig->peerGuid.FromString("1824679405"); this->selfPeerDataConfig->isHost = true; enterStage(P2PStage_Initial, NULL); } void P2PConnectManager::getIPAddress() { struct ifaddrs *interfaces = NULL; struct ifaddrs *temp_addr = NULL; int success = 0; // retrieve the current interfaces - returns 0 on success success = getifaddrs(&interfaces); if (success == 0) { // Loop through linked list of interfaces temp_addr = interfaces; while(temp_addr != NULL) { int familyType = temp_addr->ifa_addr->sa_family; if(familyType == AF_INET) { if(strcmp(temp_addr->ifa_name, "en0") == 0) { struct sockaddr_in * tempSockaddr = ((struct sockaddr_in *)temp_addr->ifa_addr); generalConfigData->selfInnerIpAddress = inet_ntoa(tempSockaddr->sin_addr); printf("the inner0 ipaddress is %s the port is %d \n",generalConfigData->selfInnerIpAddress.c_str(),((struct sockaddr_in *)temp_addr->ifa_addr)->sin_port); } else if(strcmp(temp_addr->ifa_name, "en1") == 0) { generalConfigData->selfInnerIpAddress = inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr); printf("the inner1 ipaddress is %s the port is %d \n",generalConfigData->selfInnerIpAddress.c_str(),((struct sockaddr_in *)temp_addr->ifa_addr)->sin_port); } } temp_addr = temp_addr->ifa_next; } } freeifaddrs(interfaces); } void P2PConnectManager::enterStage(P2PConnectStages stage,Packet * packet) { curConnectStage = stage; switch (stage) { case P2PStage_Initial: printf("获取本机的ip地址 \n"); getIPAddress(); break; case P2PStage_NATTypeUPNPDetection: printf("检测Nat类型... \n"); natTypeDetectionHandler->startCountDown(); this->natTypeDetectionHandler->startDetect(generalConfigData->NATCompleteServerAddress); break; case P2PStage_NATPunchThrough: natPunchThroughHandler->startCountDown(); if(this->selfPeerDataConfig->isHost) //我方发起发,主动发出穿墙请求 { printf("开始进行NAT穿透... \n"); natPunchThroughHandler->startPunch(selfPeerDataConfig->peerGuid); } else { latencyCheckIndex = 0; printf("等待小伙伴进行NAT穿透。。。。 \n"); } break; case P2PStage_ConnectToPeer: //nat穿透成功 连接peer break; case P2PStage_ConnectForwardServer: natPunchThroughHandler->isOnTimeCountingDown = false; printf("连接到转发服务器。。。。。。 \n"); this->proxyHandler->startConnectToProxyServer(); break; case P2PStage_ConnectProxyServer: printf("连接到代理服务器........... \n"); break; case P2PStage_CountLatency: printf("开始估算双方通信延迟 \n"); latencyCheckIndex = 0; break; case P2PStage_AppointStartTime: printf("开始约定游戏开始时间 \n"); if(this->selfPeerDataConfig->isHost) { BitStream bsOut; bsOut.Write((MessageID) ID_USER_AppointStartTime); TimeMS curClientTime = GetTimeMS(); bsOut.Write(curClientTime); RakNetStuff::getInstance()->rakPeer->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,this->selfPeerDataConfig->peerGuid,false); } break; case P2PStage_ConnectEnd: break; } } void P2PConnectManager::startNetWork() { this->initInfo(); RakNetStuff::getInstance(); RakNet::ConnectionAttemptResult car = RakNetStuff::rakPeer->Connect(generalConfigData->natCompleteServerIp.c_str(), generalConfigData->NatCompleteServetPort,0,0, NULL,0,12,500,4000); if(car == INVALID_PARAMETER || car == CANNOT_RESOLVE_DOMAIN_NAME || car == SECURITY_INITIALIZATION_FAILED) { printf("--------------- connect to punch server error -----------------\n"); } } void P2PConnectManager::onConnectSuccess(PeerConnectTypes connectType) { this->selfPeerDataConfig->connectType = connectType; this->enterStage(P2PStage_CountLatency); //进行延迟探测 if(this->selfPeerDataConfig->isHost) { BitStream bsOut; bsOut.Write((MessageID) ID_USER_CheckLatency); TimeMS packsetSendTime = GetTimeMS(); bsOut.Write(packsetSendTime); RakNetStuff::getInstance()->rakPeer->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,this->selfPeerDataConfig->peerGuid,false); } } void P2PConnectManager::onConnectFailed() { proxyHandler->isOnTimeCountingDown = false; printf("连接建立失败,请检查网络设置。。。。。。 \n"); return; } void P2PConnectManager::UpdateRakNet() { RakNet::Packet *packet; RakNet::TimeMS curTime = GetTimeMS(); for (packet= RakNetStuff::rakPeer->Receive(); packet; RakNetStuff::rakPeer->DeallocatePacket(packet), packet=RakNetStuff::rakPeer->Receive()) { int retCode = packet->data[0]; switch (retCode) { case ID_CONNECTION_REQUEST_ACCEPTED: //成功连接上了服务器/peer { if(this->curConnectStage == P2PStage_Initial) { this->generalConfigData->punchServerGuid = packet->guid; //连接服务器 printf("ID_CONNECTION_REQUEST_ACCEPTED to %s with GUID %s\n", packet->systemAddress.ToString(true), packet->guid.ToString()); printf("My external address is %s\n", RakNetStuff::rakPeer->GetExternalID(packet->systemAddress).ToString(true)); printf("My GUID is %s\n", RakNetStuff::rakPeer->GetMyGUID().ToString()); if(!this->selfPeerDataConfig->isHost) { HelloWorld::instance->pLabel->setString(RakNetStuff::rakPeer->GetMyGUID().ToString()); } enterStage(P2PStage_NATTypeUPNPDetection,packet); enterStage(P2PStage_NATPunchThrough,packet); } else if(this->curConnectStage == P2PStage_ConnectToPeer) { //peer to peer 连接成功 printf("连接到小伙伴 %s with GUID: %s 成功\n",packet->systemAddress.ToString(true), packet->guid.ToString()); natPunchThroughHandler->isOnTimeCountingDown = false; this->onConnectSuccess(PeerConnectType_p2p); } else if(this->curConnectStage == P2PStage_ConnectForwardServer) //连接上proxy服务器 { printf("连接上代理服务器 \n"); //开始尝试转发 proxyHandler->proxyClient->RequestForwarding(P2PConnectManager::getInstance()->generalConfigData->ProxyServerArrress, UNASSIGNED_SYSTEM_ADDRESS, this->selfPeerDataConfig->peerGuid, UDP_FORWARDER_MAXIMUM_TIMEOUT, 0); } else if(this->curConnectStage == P2PStage_ConnectProxyServer) //连接到代理服务器成功 { proxyHandler->isOnTimeCountingDown = false; this->onConnectSuccess(PeerConnectType_proxy); //通过代理连接成功 } break; } case ID_NEW_INCOMING_CONNECTION: { if(this->curConnectStage == P2PStage_ConnectToPeer) //连接到peer { printf("收到来自小伙伴 %s with GUID: %s 的连接请求\n", packet->systemAddress.ToString(true), packet->guid.ToString()); natPunchThroughHandler->isOnTimeCountingDown = false; this->onConnectSuccess(PeerConnectType_p2p); } } break; case ID_NAT_TYPE_DETECTION_RESULT: //nat类型检测得出结果 natTypeDetectionHandler->handleSinglePacket(packet); break; case ID_CONNECTION_ATTEMPT_FAILED: case ID_IP_RECENTLY_CONNECTED: case ID_INCOMPATIBLE_PROTOCOL_VERSION: case ID_NO_FREE_INCOMING_CONNECTIONS: { P2PManagerFunc::printPacketMessages(packet); if(this->curConnectStage == P2PStage_Initial) { printf("连接punchThrough服务器失败,\n"); this->enterStage(P2PStage_ConnectForwardServer); } else if(this->curConnectStage == P2PStage_NATPunchThrough || this->curConnectStage == P2PStage_ConnectToPeer) { int packetCode = packet->data[0]; const char* targetName; if (strcmp(packet->systemAddress.ToString(false),P2PConnectManager::getInstance()->generalConfigData->natCompleteServerIp.c_str())==0) { printf("NatCompleteServer 连接失败, 不能建立p2p连接 \n"); this->enterStage(P2PStage_ConnectForwardServer); } } else if(this->curConnectStage == P2PStage_ConnectForwardServer || this->curConnectStage == P2PStage_ConnectProxyServer) { proxyHandler->isOnTimeCountingDown = false; this->onConnectFailed(); } } break; #pragma NAT穿透阶段消息 //NAT 穿透系列 case ID_NAT_TARGET_NOT_CONNECTED: case ID_NAT_TARGET_UNRESPONSIVE: case ID_NAT_CONNECTION_TO_TARGET_LOST: { printf("穿墙阶段连接信息丢失..... \n"); RakNet::RakNetGUID recipientGuid; RakNet::BitStream bs(packet->data,packet->length,false); bs.IgnoreBytes(sizeof(RakNet::MessageID)); bs.Read(recipientGuid); this->enterStage(P2PStage_ConnectForwardServer); } break; case ID_NAT_ALREADY_IN_PROGRESS: //NAT Punch Through 进行中 { RakNet::RakNetGUID recipientGuid; RakNet::BitStream bs(packet->data,packet->length,false); bs.IgnoreBytes(sizeof(RakNet::MessageID)); bs.Read(recipientGuid); printf("正在向 %s 穿墙中 ....... ",recipientGuid.ToString()); } break; case ID_NAT_PUNCHTHROUGH_FAILED: printf("NATp2p 穿透失败 \n"); this->enterStage(P2PStage_ConnectForwardServer); break; case ID_NAT_PUNCHTHROUGH_SUCCEEDED: //穿墙成功 { natPunchThroughHandler->isOnTimeCountingDown = false; unsigned char weAreTheSender = packet->data[1]; this->enterStage(P2PStage_ConnectToPeer); //进入直连阶段 if (weAreTheSender) //我方是发起方 { printf("%s","穿墙成功,正在尝试建立直连 \n"); RakNet::ConnectionAttemptResult car = RakNetStuff::rakPeer->Connect(packet->systemAddress.ToString(false), packet->systemAddress.GetPort(), 0, 0); RakAssert(car==RakNet::CONNECTION_ATTEMPT_STARTED); } else { printf("成功收到穿墙请求。。。等待对方直连建立.....\n"); } } break; #pragma NAT 穿透阶段结束 #pragma 连接出错处理_Start case ID_DISCONNECTION_NOTIFICATION: case ID_CONNECTION_LOST: { P2PManagerFunc::printPacketMessages(packet); //从穿墙服务器断开 if(strcmp(packet->systemAddress.ToString(false),generalConfigData->natCompleteServerIp.c_str())==0) { printf("punchthrough 服务器断开连接 \n"); if(this->curConnectStage == P2PStage_NATPunchThrough) { printf("跳过punch through 服务器 \n"); this->enterStage(P2PStage_ConnectForwardServer); } } else if(strcmp(packet->systemAddress.ToString(false),generalConfigData->proxyServerIp.c_str())==0) { printf("proxy 服务器断开连接 \n"); if(this->curConnectStage == P2PStage_ConnectProxyServer) { printf("proxy 服务器断开连接 \n"); this->onConnectFailed(); } } else { printf("与 %s 的连接断开,pk失败 .... \n",packet->systemAddress.ToString(false)); } } break; #pragma 连接出错_End #pragma 延迟探测信息_Start case ID_USER_CheckLatency: //收到peer发来的信息 { printf(">>>>>>>>>>>>>>>> 收到延迟探测信息 \n"); TimeMS sendTime; RakNet::BitStream bs(packet->data,packet->length,false); bs.IgnoreBytes(sizeof(RakNet::MessageID)); bs.Read(sendTime); if(!this->selfPeerDataConfig->isHost) { this->selfPeerDataConfig->peerGuid = packet->guid; } BitStream bsOut; bsOut.Write((MessageID) ID_USER_CheckLatency_FeedBack); bsOut.Write(sendTime); RakNetStuff::getInstance()->rakPeer->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,this->selfPeerDataConfig->peerGuid,false); break; } case ID_USER_CheckLatency_FeedBack: //收到peer发来的信息 { printf(">>>>>>>>>>>>>>> 收到延迟探测反馈信息 \n"); TimeMS curtime = GetTimeMS(); TimeMS sendTime; RakNet::BitStream bs(packet->data,packet->length,false); bs.IgnoreBytes(sizeof(RakNet::MessageID)); bs.Read(sendTime); uint32_t latencyTime = curtime - sendTime; //延迟时间 latencyCheckIndex++; selfPeerDataConfig->averagePeerLatency += latencyTime; printf("单次延迟时间为: %d \n",latencyTime); if(SINGLE_MAXLATENCY_CHECKTIME == latencyCheckIndex) { BitStream bsOut; bsOut.Write((MessageID) ID_USER_NotifySelfLatency); bsOut.Write(selfPeerDataConfig->averagePeerLatency); RakNetStuff::getInstance()->rakPeer->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,this->selfPeerDataConfig->peerGuid,false); if(!this->selfPeerDataConfig->isHost) { this->selfPeerDataConfig->averagePeerLatency = this->selfPeerDataConfig->averagePeerLatency / 2 / SINGLE_MAXLATENCY_CHECKTIME / 2; printf("-----------平均延时为 %d \n",this->selfPeerDataConfig->averagePeerLatency); this->enterStage(P2PStage_AppointStartTime); } } else //继续发送延迟测试信息 { BitStream bsOut; bsOut.Write((MessageID) ID_USER_CheckLatency); TimeMS packsetSendTime = GetTimeMS(); bsOut.Write(packsetSendTime); RakNetStuff::getInstance()->rakPeer->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,this->selfPeerDataConfig->peerGuid,false); } break; } case ID_USER_NotifySelfLatency: { uint32_t peerlatency; RakNet::BitStream bs(packet->data,packet->length,false); bs.IgnoreBytes(sizeof(RakNet::MessageID)); bs.Read(peerlatency); printf("收到对方peer的游戏延迟反馈信息 \n"); if(this->selfPeerDataConfig->isHost) //收到被动方的延迟信息,可以进入开始游戏阶段 { this->selfPeerDataConfig->averagePeerLatency = peerlatency / 2 / SINGLE_MAXLATENCY_CHECKTIME / 2; printf("++++++++++平均延时为 %d \n",this->selfPeerDataConfig->averagePeerLatency); this->enterStage(P2PStage_AppointStartTime); } else //收到主动发的延迟信息,从我方开始测试 { this->selfPeerDataConfig->averagePeerLatency = peerlatency; //我方发送延迟探测信息 BitStream bsOut; bsOut.Write((MessageID) ID_USER_CheckLatency); TimeMS packsetSendTime = GetTimeMS(); bsOut.Write(packsetSendTime); RakNetStuff::getInstance()->rakPeer->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,this->selfPeerDataConfig->peerGuid,false); } break; } #pragma 延迟探测信息_End #pragma 约定游戏开始时间 case ID_USER_AppointStartTime: //收到 host发来的约定消息 { RakNet::BitStream bs(packet->data,packet->length,false); bs.IgnoreBytes(sizeof(RakNet::MessageID)); TimeMS peerTime; bs.Read(peerTime); BitStream bsOut; bsOut.Write((MessageID) ID_USER_AppointStartTimeBack); TimeMS purewaitTime = this->selfPeerDataConfig->averagePeerLatency * 200; bsOut.Write(peerTime + purewaitTime + this->selfPeerDataConfig->averagePeerLatency * 2); this->nextActionTime = GetTimeMS() + purewaitTime + this->selfPeerDataConfig->averagePeerLatency; RakNetStuff::getInstance()->rakPeer->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,this->selfPeerDataConfig->peerGuid,false); break; } case ID_USER_AppointStartTimeBack: //host 收到对方返回的约定消息时间 { RakNet::BitStream bs(packet->data,packet->length,false); bs.IgnoreBytes(sizeof(RakNet::MessageID)); bs.Read(this->nextActionTime); break; } #pragma 约定时间开始结束 } } if(curTime > natTypeDetectionHandler->timeMileStone) //此handler执行时间已经过期 { natTypeDetectionHandler->onTimeOutHandler(); } if(curTime > natPunchThroughHandler->timeMileStone) //此handler执行时间已经过期 { natPunchThroughHandler->onTimeOutHandler(); } if(curTime > proxyHandler->timeMileStone) //此handler执行时间已经过期 { proxyHandler->onTimeOutHandler(); } if(this->nextActionTime > 0) { if(curTime >= nextActionTime) { nextActionTime = -1; printf("$$$$$$$$$$$$$$$$$$$$$ 开始游戏 $$$$$$$$$$$$$$$$$$$$$$"); } } } P2PConnectManager::~P2PConnectManager() { }<file_sep>/ios-p2ptest/Classes/p2pnetwork/P2PManagerFunc.h // // Created by 沈冬冬 on 14-2-20. // // #ifndef __P2PManagerFunc_H_ #define __P2PManagerFunc_H_ #include <iostream> #include "RakPeerInterface.h" using namespace RakNet; class P2PManagerFunc { public: P2PManagerFunc(); //输出packet信息(error 信息 ) static void printPacketMessages(Packet *packet); virtual ~P2PManagerFunc(); }; #endif //__P2PManagerFunc_H_ <file_sep>/ios-p2ptest/Classes/ReplicaManager3Irrlicht.h // // Created by 沈冬冬 on 14-2-12. // // #ifndef __ReplicaManager3Irrlicht_H_ #define __ReplicaManager3Irrlicht_H_ #include <iostream> #include "Rand.h" #include "ReplicaManager3.h" using namespace RakNet; class CDemo; class Connection_RM3Irrlicht : public RakNet::Connection_RM3 { public: Connection_RM3Irrlicht(const SystemAddress &_systemAddress,RakNetGUID _guid, CDemo *_demo):Connection_RM3(_systemAddress, _guid) { demo=_demo; } virtual ~Connection_RM3Irrlicht() {}; virtual RakNet::Replica3 *AllocReplica(RakNet::BitStream *allocationId, RakNet::ReplicaManager3 *replicaManager3); protected: CDemo *demo; }; class ReplicaManager3Irrlicht : public RakNet::ReplicaManager3 { public: CDemo *demo; ReplicaManager3Irrlicht(); virtual ~ReplicaManager3Irrlicht(); virtual Connection_RM3 *AllocConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID) const; virtual void DeallocConnection(Connection_RM3 *connection) const; }; #endif //__ReplicaManager3Irrlicht_H_ <file_sep>/ios-p2ptest/Classes/p2pnetwork/BaseStageHandler.cpp // // BaseStageHandler.cpp // ios-p2ptest // // Created by 沈冬冬 on 14-2-14. // // #include "BaseStageHandler.h" BaseStageHandler::BaseStageHandler(): packet(NULL), isTimeUp(false), isOnTimeCountingDown(false), timeMileStone(0) { } void BaseStageHandler::startCountDown() { this->isOnTimeCountingDown = true; } void BaseStageHandler::handleSinglePacket(Packet *packet) { this->packet = packet; } void BaseStageHandler::onTimeOutHandler() { this->isTimeUp = true; } BaseStageHandler::~BaseStageHandler() { } <file_sep>/ios-p2ptest/Classes/p2pnetwork/BaseStageHandler.h // // BaseStageHandler.h // ios-p2ptest // // Created by 沈冬冬 on 14-2-14. // // #ifndef __ios_p2ptest__BaseStageHandler__ #define __ios_p2ptest__BaseStageHandler__ #include <iostream> #include "RakMemoryOverride.h" #include "RakNetTypes.h" #include "P2PDefines.h" using namespace RakNet; class BaseStageHandler { public: TimeMS timeMileStone; //过时的时间点 bool isOnTimeCountingDown; //是否在倒计时 bool isTimeUp; //是否已经超时 P2PConnectStages currentStage; Packet *packet; BaseStageHandler(); virtual void startCountDown(); virtual void handleSinglePacket(Packet *packet); virtual void onTimeOutHandler(); virtual ~BaseStageHandler(); }; #endif /* defined(__ios_p2ptest__BaseStageHandler__) */ <file_sep>/ios-p2ptest/Classes/P2PDefines.h // // RakNetDefines.h // ios-p2ptest // // Created by 沈冬冬 on 14-2-14. // // #ifndef ios_p2ptest_RakNetDefines_h #define ios_p2ptest_RakNetDefines_h #define DEFAULT_NAT_PUNCHTHROUGH_FACILITATOR_PORT 61111 #define DEFAULT_NAT_PUNCHTHROUGH_FACILITATOR_IP "192.168.127.12" //#define DEFAULT_NAT_PUNCHTHROUGH_FACILITATOR_IP "172.26.192.231" //#define DEFAULT_NAT_PUNCHTHROUGH_FACILITATOR_IP "natpunch.jenkinssoftware.com" //#define DEFAULT_NAT_PUNCHTHROUGH_FACILITATOR_IP "172.16.17.32" #define DEFAULT_UDPPROXY_PORT 61111 #define DEFAULT_UDPPROXY_IP "192.168.127.12" const int SINGLE_MAXLATENCY_CHECKTIME = 5; //p2p连接的几个阶段 enum P2PConnectStages { P2PStage_Initial, P2PStage_NATTypeUPNPDetection, //nat类型检测 + UPNP检测 P2PStage_NATPunchThrough, //对目标客户端进行穿墙连接 目标客户端需要和本机连接在一台punchthrough服务器上 P2PStage_ConnectToPeer, //连接到指定GUID的目标 P2PStage_ConnectForwardServer, //连接到转发服务器 P2PStage_ConnectProxyServer, //连接到代理服务器 P2PStage_CountLatency, //计算延迟 P2PStage_AppointStartTime, //客户端校验时间 P2PStage_ConnectEnd }; #define STATIC_GET_SINGLEINSTANCE(Type) public: static Type* getInstance() { \ static Type* instance = NULL; \ if(instance == NULL) \ { \ instance = new Type(); \ } \ return instance; \ } #endif <file_sep>/ios-p2ptest/Classes/p2pnetwork/NatTypeDetecteUPNPHandler.h // // Created by 沈冬冬 on 14-2-14. // // #ifndef __NatTypeDetectionHandler_H_ #define __NatTypeDetectionHandler_H_ #include <iostream> #include "BaseStageHandler.h" #include "NatTypeDetectionClient.h" #include "RakNetDefines.h" #define executeMaxTime 4500 struct UPNPOpenWorkerArgs { char buff[256]; unsigned short portToOpen; unsigned int timeout; void *userData; void (*resultCallback)(bool success, unsigned short portToOpen, void *userData); void (*progressCallback)(const char *progressMsg, void *userData); }; //检测client的Nat类型 class NatTypeDetecteUPNPHandler : public BaseStageHandler{ private: NatTypeDetectionClient *natTypeDetectionClient; public: int isTypedectedFinished; int isUpnpFinished; public: NatTypeDetecteUPNPHandler(); void UPNPOpenAsynch(unsigned short portToOpen, unsigned int timeout, void (*progressCallback)(const char *progressMsg, void *userData), void (*resultCallback)(bool success, unsigned short portToOpen, void *userData), void *userData ); void startDetect(SystemAddress address); virtual ~NatTypeDetecteUPNPHandler(); virtual void handleSinglePacket(Packet *packet) override; virtual void startCountDown() override; virtual void onTimeOutHandler() override; }; #endif //__NatTypeDetectionHandler_H_ <file_sep>/ios-p2ptest/Classes/BaseIrrlichtReplica.cpp // // Created by 沈冬冬 on 14-2-12. // // #include "BaseIrrlichtReplica.h" BaseIrrlichtReplica::BaseIrrlichtReplica() { } BaseIrrlichtReplica::~BaseIrrlichtReplica() { } void BaseIrrlichtReplica::SerializeConstruction(RakNet::BitStream *constructionBitstream, RakNet::Connection_RM3 *destinationConnection) { // constructionBitstream->Write(position); } bool BaseIrrlichtReplica::DeserializeConstruction(RakNet::BitStream *constructionBitstream, RakNet::Connection_RM3 *sourceConnection) { // constructionBitstream->Read(position); return true; } RM3SerializationResult BaseIrrlichtReplica::Serialize(RakNet::SerializeParameters *serializeParameters) { return RM3SR_BROADCAST_IDENTICALLY; } void BaseIrrlichtReplica::Deserialize(RakNet::DeserializeParameters *deserializeParameters) { } void BaseIrrlichtReplica::Update(RakNet::TimeMS curTime) { } <file_sep>/ios-p2ptest/Classes/p2pnetwork/NatTypeDetecteUPNPHandler.cpp // // Created by 沈冬冬 on 14-2-14. // // #include "NatTypeDetecteUPNPHandler.h" #include "P2PConnectManager.h" #include "GetTime.h" #include "miniupnpc.h" #include "upnpcommands.h" #include "upnperrors.h" #include "Itoa.h" NatTypeDetecteUPNPHandler::NatTypeDetecteUPNPHandler(): isTypedectedFinished(0), isUpnpFinished(0) { currentStage = P2PStage_NATTypeUPNPDetection; natTypeDetectionClient = NatTypeDetectionClient::GetInstance(); RakNetStuff::getInstance()->rakPeer->AttachPlugin(natTypeDetectionClient); } void NatTypeDetecteUPNPHandler::startCountDown() { BaseStageHandler::startCountDown(); this->timeMileStone = GetTimeMS() + executeMaxTime; } void NatTypeDetecteUPNPHandler::onTimeOutHandler() { if(!this->isOnTimeCountingDown || this->isTimeUp) return; BaseStageHandler::onTimeOutHandler(); if(!isTypedectedFinished) printf("nat类型检测超时... \n"); if(!isUpnpFinished) printf("upnp绑定超时... \n"); } void UPNPProgressCallback(const char *progressMsg, void *userData) { printf(progressMsg); } void UPNPResultCallback(bool success, unsigned short portToOpen, void *userData) { P2PConnectManager::getInstance()->natTypeDetectionHandler->isUpnpFinished = 1; if(P2PConnectManager::getInstance()->natTypeDetectionHandler->isTypedectedFinished) P2PConnectManager::getInstance()->natTypeDetectionHandler->isOnTimeCountingDown = false; if (success) { P2PConnectManager::getInstance()->generalConfigData->clientNatType = NAT_TYPE_SUPPORTS_UPNP; printf("upbp 端口映射成功 p2p连接可能增加。。。 \n"); } else { printf("upnp 绑定失败。。。\n"); } } void NatTypeDetecteUPNPHandler::startDetect(SystemAddress address) { if(this->isTimeUp) return; isTypedectedFinished = 0; isUpnpFinished = 0; natTypeDetectionClient->DetectNATType(address); DataStructures::List<RakNetSocket2* > sockets; RakNetStuff::rakPeer->GetSockets(sockets); this->UPNPOpenAsynch(sockets[0]->GetBoundAddress().GetPort(), executeMaxTime,UPNPProgressCallback,UPNPResultCallback,0); } void NatTypeDetecteUPNPHandler::handleSinglePacket(Packet *packet) { if(this->isTimeUp) return; BaseStageHandler::handleSinglePacket(packet); int dataType = packet->data[0]; if(ID_NAT_TYPE_DETECTION_RESULT == dataType) { isTypedectedFinished = 1; NATTypeDetectionResult result = (RakNet::NATTypeDetectionResult) packet->data[1]; printf("NAT Type is %s (%s)\n", NATTypeDetectionResultToString(result), NATTypeDetectionResultToStringFriendly(result)); if (result == RakNet::NAT_TYPE_PORT_RESTRICTED) { printf("端口受限型cone 可穿透 但依赖于upnp的实现 .\n"); } else if(result == NAT_TYPE_SYMMETRIC) { printf("对称性的NAT,p2p 穿透直连基本宣告失败"); } if(isUpnpFinished) this->isOnTimeCountingDown = false; P2PConnectManager::getInstance()->generalConfigData->clientNatType = result; // if (result != RakNet::NAT_TYPE_NONE) //存在NAT的情形,需要打开upnp操作 // { // P2PConnectManager::getInstance()->enterStage(P2PStage_UPNP); // } // else //不存在NAT 这种情况基本不可能 // { // P2PConnectManager::getInstance()->enterStage(P2PStage_NATPunchThrough); //直接进入连接服务器阶段 // } } } RAK_THREAD_DECLARATION(UPNPOpenWorker) { UPNPOpenWorkerArgs *args = ( UPNPOpenWorkerArgs * ) arguments; bool success=false; struct UPNPDev * devlist = 0; RakNet::Time t1 = GetTime(); devlist = upnpDiscover(args->timeout, 0, 0, 0, 0, 0); RakNet::Time t2 = GetTime(); if (devlist) { if (args->progressCallback) args->progressCallback("List of UPNP devices found on the network :\n", args->userData); struct UPNPDev * device; for(device = devlist; device; device = device->pNext) { sprintf(args->buff, " desc: %s\n st: %s\n\n", device->descURL, device->st); if (args->progressCallback) args->progressCallback(args->buff, args->userData); } char lanaddr[64]; /* my ip address on the LAN */ struct UPNPUrls urls; struct IGDdatas data; if (UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr))==1) { char iport[32]; Itoa(args->portToOpen, iport,10); char eport[32]; strcpy(eport, iport); // Version miniupnpc-1.6.20120410 int r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, eport, iport, lanaddr, 0, "UDP", 0, "0"); if(r!=UPNPCOMMAND_SUCCESS) printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n", eport, iport, lanaddr, r, strupnperror(r)); char intPort[6]; char intClient[16]; // Version miniupnpc-1.6.20120410 char desc[128]; char enabled[128]; char leaseDuration[128]; r = UPNP_GetSpecificPortMappingEntry(urls.controlURL, data.first.servicetype, eport, "UDP", intClient, intPort, desc, enabled, leaseDuration); if(r!=UPNPCOMMAND_SUCCESS) { sprintf(args->buff, "GetSpecificPortMappingEntry() failed with code %d (%s)\n", r, strupnperror(r)); if (args->progressCallback) args->progressCallback(args->buff, args->userData); } else { if (args->progressCallback) args->progressCallback("UPNP success.\n", args->userData); // game->myNatType=NAT_TYPE_SUPPORTS_UPNP; success=true; } } } if (args->resultCallback) args->resultCallback(success, args->portToOpen, args->userData); RakNet::OP_DELETE(args, _FILE_AND_LINE_); return 0; } void NatTypeDetecteUPNPHandler::UPNPOpenAsynch(unsigned short portToOpen, unsigned int timeout, void (*progressCallback)(const char *progressMsg, void *userData), void (*resultCallback)(bool success, unsigned short portToOpen, void *userData), void *userData ) { UPNPOpenWorkerArgs *args = RakNet::OP_NEW<UPNPOpenWorkerArgs>(_FILE_AND_LINE_); args->portToOpen = portToOpen; args->timeout = timeout; args->userData = userData; args->progressCallback = progressCallback; args->resultCallback = resultCallback; RakThread::Create(UPNPOpenWorker, args); } NatTypeDetecteUPNPHandler::~NatTypeDetecteUPNPHandler() { NatTypeDetectionClient::DestroyInstance(natTypeDetectionClient); }
98b9c3ce464dc4faf71ae813cf842b4b576bab79
[ "C", "C++" ]
21
C++
AllenShen/ios-p2ptest
3430b0c1dc122a4ba68d79ad1da9a51ea268e85e
acb8bfd66baa5036a1a0d0d35f663efe39369b0d
refs/heads/master
<repo_name>Rinaloving/NPoco<file_sep>/README.md # NPoco C# <file_sep>/NpocoDemo/NpocoDemo/Program.cs using NPoco; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NpocoDemo { class Program { static void Main(string[] args) { #region 连接sqlserver 数据库 //using (IDatabase db = new Database("sqlserver")) //{ // List<Person> users = db.Fetch<Person>("select Name, IDType from Person"); // foreach (var item in users) // { // // Console.WriteLine(item.Name+" " +item.IDType); // } //} #endregion #region 连接oracle 数据库 //using (IDatabase db = new Database("ssss")) //{ // try // { // List<STAFF> users = db.Fetch<STAFF>("select STAFF_ID, STAFF_NAME from STAFF"); // foreach (var item in users) // { // Console.WriteLine(item.STAFF_ID + " " + item.STAFF_NAME); // } // } // catch (Exception ex) // { // throw; // } //} #endregion #region 通过id查询 //IDatabase db = new Database("ssss"); //STAFF staff = db.SingleById<STAFF>(7); //这里指主键,我们没有指定主键,所以它不知道 //Console.WriteLine(staff.STAFF_NAME); #endregion #region via Sql (通过sql语句查找) //IDatabase db = new Database("ssss"); //STAFF staff = db.Single<STAFF>("WHERE STAFF_ID =@0", 7); //Console.WriteLine(staff.STAFF_NAME); //OK #endregion #region 插入数据 //IDatabase db2 = new Database("estate"); //STAFFPERMISSON st = new STAFFPERMISSON(); //st.STAFFID = "66"; //st.STAFFNAME = "蜡笔小新"; //st.ISPROMISE = 1; //db2.Insert<STAFFPERMISSON>("STAFFPERMISSON", "STAFFID",false, st); #endregion #region 读取数据 与更新数据 //IDatabase db = new Database("ssss"); //var staff = db.SingleById<STAFF>(7); //staff.STAFF_NAME = "海绵宝宝"; //db.Update(staff); //Console.WriteLine(staff.STAFF_ID+" : "+staff.STAFF_NAME); #endregion #region 删除数据 //IDatabase db = new Database("estate"); //var staffpermission = db.SingleById<STAFFPERMISSON>(66); //db.Delete(staffpermission); //db.Delete<STAFFPERMISSON>(1); #endregion #region 插入或更新数据 //IDatabase db = new Database("estate"); //STAFFPERMISSON sn = new STAFFPERMISSON() //{ // STAFFID = "23", // STAFFNAME = "大力水手", // ISPROMISE = 1 //}; //db.Save(sn); #endregion #region 查询集合 IDatabase db = new Database("ssss"); //Eager(热切的,渴望的) List<STAFF> staff = db.Fetch<STAFF>(); //Fetch all Console.WriteLine(staff.Count.ToString()); List<STAFF> staff2 = db.Fetch<STAFF>("WHERE STAFF_ID = 7"); foreach (var item in staff2) { Console.WriteLine(item.STAFF_NAME); } List<STAFF> staff3 = db.Fetch<STAFF>("SELECT * FROM STAFF WHERE STAFF_ID = 7"); foreach (var item in staff3) { Console.WriteLine(item.STAFF_NAME); } //Lazy List<STAFF> staff4 = db.Query<STAFF>("SELECT * FROM STAFF WHERE STAFF_ID = 7") as List<STAFF>; // 类型转换异常 foreach (var item in staff4) { Console.WriteLine(item.STAFF_NAME); } #endregion Console.ReadKey(); } } public class Person { public string Name { get; set; } public string IDType { get; set; } } //Mapping 关系 [TableName("STAFF")] [PrimaryKey("STAFF_ID")] //加了之后,就可以通过ID来查询了 public class STAFF { [Column("STAFF_ID")] public int STAFF_ID { get; set; } public string STAFF_NAME { get; set; } } [TableName("STAFFPERMISSON")] [PrimaryKey("STAFFID")] public class STAFFPERMISSON { //[Column("STAFFID")] public string STAFFID { get; set; } [Column("STAFFNAME")] public string STAFFNAME { get; set; } [Column("ISPROMISE")] public int ISPROMISE { get; set; } //public STAFFPERMISSON(string _staffid, string _staffname, int _ispromise) //{ // this.STAFFID = _staffid; // this.STAFFNAME = _staffname; // this.ISPROMISE = _ispromise; //} } }
707a5ea4e81e92fcb0e97948fa8f9f24e7540872
[ "Markdown", "C#" ]
2
Markdown
Rinaloving/NPoco
16be532cea83ecb9e2e907d36b65ad86f596b3ea
18ce987b0052d8fd08a5823e9b682cfd3082044a
refs/heads/master
<file_sep>bootnodes=["enode://6ad4d78f7ada3ac6a03e11c5397242851c3730e44920ef5c8cfff4810de01c1e04f8e85fcab958dfed32b1cff2b7b4500751aa4ddd46daa1827d833046c65b94@127.0.0.1:30303"] p2p-port="30306" rpc-http-enabled=true rpc-http-host="0.0.0.0" rpc-http-api=["ADMIN,ETH,NET,WEB3,IBFT,PERM,DEBUG,MINER,EEA,PRIV,TXPOOL"] rpc-http-cors-origins=["all"] rpc-http-port="22003" host-whitelist=["*"] <file_sep>#!/bin/bash set -u set -e echo "[*] Starting Hyperledger Besu nodes" GENESIS=~/besu-node/data/genesis.json NODE_CONF=~/besu-node/data/configs LOGS=~/besu-chain/logs NODE_DATA=~/besu-chain/data/Node-1/data besu --data-path="$NODE_DATA" --genesis-file="$GENESIS" --config-file="$NODE_CONF"/node1.toml >> "$LOGS"/1.log & sleep 5 NODE_DATA=~/besu-chain/data/Node-2/data besu --data-path="$NODE_DATA" --genesis-file="$GENESIS" --config-file="$NODE_CONF"/node2.toml >> "$LOGS"/2.log & sleep 5 NODE_DATA=~/besu-chain/data/Node-3/data besu --data-path="$NODE_DATA" --genesis-file="$GENESIS" --config-file="$NODE_CONF"/node3.toml >> "$LOGS"/3.log & sleep 5 NODE_DATA=~/besu-chain/data/Node-4/data besu --data-path="$NODE_DATA" --genesis-file="$GENESIS" --config-file="$NODE_CONF"/node4.toml >> "$LOGS"/4.log & sleep 5 echo "[*] Waiting for nodes to start" sleep 15 echo "All nodes started. See '~/besu-chain/logs' for logs, and run e.g. 'geth attach http://127.0.0.1:22000' to attach to the first Geth node." <file_sep>#!/bin/bash set -u set -e echo "[*] Cleaning up temporary data directories" rm -rf ~/besu-chain/data rm -rf ~/besu-chain/logs mkdir -p ~/besu-chain/logs NODE_NAME="Node-1" echo "[*] Configuring node $NODE_NAME" mkdir -p ~/besu-chain/data/"$NODE_NAME"/data/ cp ~/besu-node/data/keys/tm1 ~/besu-chain/data/"$NODE_NAME"/data/key cp ~/besu-node/data/keys/tm1.pub ~/besu-chain/data/"$NODE_NAME"/data/key.pub NODE_NAME="Node-2" echo "[*] Configuring node $NODE_NAME" mkdir -p ~/besu-chain/data/"$NODE_NAME"/data/ cp ~/besu-node/data/keys/tm2 ~/besu-chain/data/"$NODE_NAME"/data/key cp ~/besu-node/data/keys/tm2.pub ~/besu-chain/data/"$NODE_NAME"/data/key.pub NODE_NAME="Node-3" echo "[*] Configuring node $NODE_NAME" mkdir -p ~/besu-chain/data/"$NODE_NAME"/data/ cp ~/besu-node/data/keys/tm3 ~/besu-chain/data/"$NODE_NAME"/data/key cp ~/besu-node/data/keys/tm3.pub ~/besu-chain/data/"$NODE_NAME"/data/key.pub NODE_NAME="Node-4" echo "[*] Configuring node $NODE_NAME" mkdir -p ~/besu-chain/data/"$NODE_NAME"/data/ cp ~/besu-node/data/keys/tm4 ~/besu-chain/data/"$NODE_NAME"/data/key cp ~/besu-node/data/keys/tm4.pub ~/besu-chain/data/"$NODE_NAME"/data/key.pub echo "[*] Initialization was completed successfully." set +u set +e <file_sep># besu-node Instalación y configuración de un nodo Blockcheq en una red Hyperledger Besu <file_sep>#!/bin/bash function superuser { if ( type "sudo" > /dev/null 2>&1 ) then sudo $@ else eval $@ fi } function rhrequired { superuser yum clean all superuser yum -y update # Check EPEL repository availability. It is available by default in Fedora and CentOS, but it requires manual # installation in RHEL EPEL_AVAILABLE=$(superuser yum search epel | grep release || true) if [[ -z $EPEL_AVAILABLE ]];then echo "EPEL Repository is not available via YUM. Downloading" superuser yum -y install wget wget https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm -O /tmp/epel-release-latest-7.noarch.rpm superuser yum -y install /tmp/epel-release-latest-7.noarch.rpm else echo "EPEL repository is available in YUM via distro packages. Adding it as a source for packages" superuser yum -y install epel-release fi superuser yum -y update echo "Installing Libraries" curl -sL https://rpm.nodesource.com/setup_10.x | superuser bash - superuser yum -y install gmp-devel gcc gcc-c++ make openssl-devel libdb-devel\ ncurses-devel wget nmap-ncat libsodium-devel libdb-devel leveldb-devel nodejs npm install [email protected] JDK_URL="https://download.oracle.com/otn-pub/java/jdk/13.0.1+9/cec27d702aa74d5a8630c65ae61e4305/jdk-13.0.1_linux-x64_bin.rpm" wget --no-check-certificate -c --header "Cookie: oraclelicense=accept-securebackup-cookie" $JDK_URL -O /tmp/jdk_linux-x64_bin.rpm pushd /tmp superuser yum -y install jdk_linux-x64_bin.rpm popd rm -rf /tmp/jdk_linux-x64_bin.rpm export JAVA_HOME=/usr/java/jdk-13.0.1 } function debrequired { superuser apt-get update && superuser apt-get upgrade -y superuser apt-get install -y curl curl -sL https://deb.nodesource.com/setup_10.x | superuser bash - superuser apt-get install -y software-properties-common unzip wget git\ make gcc libsodium-dev build-essential libdb-dev zlib1g-dev \ libtinfo-dev sysvbanner psmisc libleveldb-dev\ libsodium-dev libdb5.3-dev nodejs superuser npm install [email protected] JDK_URL="https://download.oracle.com/otn-pub/java/jdk/13.0.1+9/cec27d702aa74d5a8630c65ae61e4305/jdk-13.0.1_linux-x64_bin.deb" wget --no-check-certificate -c --header "Cookie: oraclelicense=accept-securebackup-cookie" $JDK_URL -O /tmp/jdk_linux-x64_bin.deb pushd /tmp superuser dpkg -i jdk_linux-x64_bin.deb popd rm -rf /tmp/jdk_linux-x64_bin.deb export JAVA_HOME=/usr/lib/jvm/jdk-13.0.1 } function installbesu { if ( ! type "besu" > /dev/null 2>&1 ) then echo "Installing HYPERLEDGER BESU" pushd /tmp git clone --recursive https://github.com/hyperledger/besu.git cd besu git checkout 59096789cefefa6e8210e091dbe7ecdd9b1d8163 ./gradlew build -x test cd build/distributions/ tar -xzf besu-1.3.5-SNAPSHOT.tar.gz superuser cp besu-1.3.5-SNAPSHOT/bin/besu /usr/local/bin/ superuser cp besu-1.3.5-SNAPSHOT/lib/* /usr/local/lib/ popd rm -rf /tmp/besu unset JAVA_HOME fi } function rhconfigurepath { # Manage JAVA_HOME variable if [[ -z "$JAVA_HOME" ]]; then echo 'export JAVA_HOME=/usr/java/jdk-13.0.1' >> $HOME/.bashrc export JAVA_HOME=/usr/java/jdk-13.0.1 export PATH=$JAVA_HOME/bin:$PATH echo "[*] JAVA_HOME = $JAVA_HOME" fi exec "$BASH" } function debconfigurepath { # Manage JAVA_HOME variable if [[ -z "$JAVA_HOME" ]]; then echo 'export JAVA_HOME=/usr/lib/jvm/jdk-13.0.1' >> $HOME/.bashrc export JAVA_HOME=/usr/lib/jvm/jdk-13.0.1 export PATH=$JAVA_HOME/bin:$PATH echo "[*] JAVA_HOME = $JAVA_HOME" fi exec "$BASH" } function uninstallblockcheq { superuser rm /usr/local/bin/besu 2>/dev/null superuser rm /usr/local/lib/*.jar 2>/dev/null rm -rf /tmp/* 2>/dev/null } function installblockcheq { set -e OS=$(cat /etc/os-release | grep "^ID=" | sed 's/ID=//g' | sed 's\"\\g') if [ $OS = "centos" ] || [ $OS = "rhel" ] then rhrequired elif [ $OS = "ubuntu" ];then debrequired else echo 'This operating system is not yet supported' exit fi installbesu if [ $OS = "centos" ] || [ $OS = "rhel" ] then rhconfigurepath elif [ $OS = "ubuntu" ];then debconfigurepath fi set +e } if ( [ "uninstall" == "$1" ] ) then uninstallblockcheq elif ( [ "reinstall" == "$1" ] ) then uninstallblockcheq installblockcheq else installblockcheq fi echo "[*] Bootstrapping was completed successfully." <file_sep>#!/bin/bash set -e pkill -f java set +e<file_sep>bootnodes=[] p2p-port="30303" rpc-http-enabled=true rpc-http-host="0.0.0.0" rpc-http-api=["ADMIN,ETH,NET,WEB3,IBFT,PERM,DEBUG,MINER,EEA,PRIV,TXPOOL"] rpc-http-cors-origins=["all"] rpc-http-port="22000" host-whitelist=["*"] min-gas-price=0
0bed309c2275a92c69fd8a4ad8f17707bb154b91
[ "TOML", "Markdown", "Shell" ]
7
TOML
blockcheq/besu-node
c30e38f7f139d5b9f233de6cbf72c4f9d2000109
7720658d3d3e13f35b04913ff391532ee4fc1b9f
refs/heads/master
<file_sep> var bio = { 'name': '<NAME>', 'role': 'Web Developer', 'contacts': { 'mobile': '(650)-380-4377', 'email': '<EMAIL>', 'github': 'markghsu', 'twitter': 'http://twitter.com/markghsu', 'location': 'Tustin, CA' }, 'welcomeMessage': 'Hello World!', 'skills':['php','javascript','C#','HTML','CSS'], 'biopic':'images/me.jpg', 'display': function f(){ $('#topContacts').prepend(HTMLemail.replace("%data%", this.contacts.email)) .prepend(HTMLmobile.replace("%data%", this.contacts.mobile)) .prepend(HTMLgithub.replace("%data%", this.contacts.github)) .prepend(HTMLtwitter.replace("%data%", this.contacts.twitter)) .prepend(HTMLlocation.replace("%data%", this.contacts.location)); $('#header').prepend(HTMLheaderRole.replace("%data%", this.role)) .prepend(HTMLheaderName.replace("%data%", this.name)) .append(HTMLwelcomeMsg.replace("%data%", this.welcomeMessage)) .append(HTMLbioPic.replace("%data%", this.biopic)) .append(HTMLskillsStart); $.each(this.skills,function f(index,value){$('#skills').append(HTMLskills.replace("%data%", value));}); $('#footerContacts').append(HTMLemail.replace("%data%", this.contacts.email)) .append(HTMLmobile.replace("%data%", this.contacts.mobile)) .append(HTMLgithub.replace("%data%", this.contacts.github)) .append(HTMLtwitter.replace("%data%", this.contacts.twitter)) .append(HTMLlocation.replace("%data%", this.contacts.location)); } }; var projects = { 'projects': [{ 'title': 'TMK Keyboard', 'dates': 'Jun. - Aug. 2015', 'description': 'Created a mechanical keyboard from scratch. Ordered laser cut acrylic, soldered diodes to keys and connected to Teensy board. Used https://github.com/tmk/tmk_keyboard firmware to control/map keys.', 'images': ['images/image1.jpg','images/image2.jpg'] }], 'display': function f(){ $.each(this.projects, function f(index,value){ var myhtml = $.parseHTML(HTMLprojectStart); $(myhtml).append(HTMLprojectTitle.replace('%data%', value.title)) .append(HTMLprojectDates.replace('%data%', value.dates)) .append(HTMLprojectDescription.replace('%data%', value.description)); $.each(value.images, function f(ind,img){ $(myhtml).append(HTMLprojectImage.replace('%data%', img)); }); $('#projects').append(myhtml); }); } }; var education = { 'schools': [{ 'name': 'UCLA', 'location': 'Los Angeles, CA', 'degree': 'B.S.', 'majors': ['Mechanical Engineering'], 'dates': '2011', 'url': 'http://ucla.edu' }], 'onlineCourses': [{ 'title': 'Front End Web Developer', 'school': 'Udacity', 'date': 'ongoing', 'url': 'http://udacity.com' }], 'display': function f() { $.each(this.schools, function f(index, value){ var myhtml = $.parseHTML(HTMLschoolStart); $(myhtml).append(HTMLschoolName.replace('%data%', value.name) + HTMLschoolDegree.replace('%data%', value.degree)) .append(HTMLschoolDates.replace('%data%', value.dates)) .append(HTMLschoolLocation.replace('%data%', value.location)) .append(HTMLschoolMajor.replace('%data%', value.majors[0])); $('#education').append(myhtml); }); if(this.onlineCourses.length) { $('#education').append(HTMLonlineClasses); $.each(this.onlineCourses, function f(index, value){ var myhtml = $.parseHTML(HTMLschoolStart); $(myhtml).append(HTMLonlineTitle.replace('%data%', value.title) + HTMLonlineSchool.replace('%data%', value.school)) .append(HTMLonlineDates.replace('%data%', value.date)) .append(HTMLonlineURL.replace('%data%', value.url)); $('#education').append(myhtml); }); } } }; var work = { 'jobs': [{ 'employer': 'MeridianLink', 'title': 'Software Automation Engineer', 'location': 'Costa Mesa, CA', 'dates': 'Aug. 2012 - Nov. 2015', 'description': 'Used rule-based logic programming language to create mortgage programs within company software. Additionally created small C# programs to download rate sheets from investor websites.' }], 'display': function f(){ $.each(this.jobs, function f(index,value){ var myhtml = $.parseHTML(HTMLworkStart); $(myhtml).append(HTMLworkEmployer.replace('%data%', value.employer) + HTMLworkTitle.replace('%data%', value.title)) .append(HTMLworkDates.replace('%data%', value.dates)) .append(HTMLworkLocation.replace('%data%', value.location)) .append(HTMLworkDescription.replace('%data%', value.description)); $('#workExperience').append(myhtml); }); } }; bio.display(); work.display(); projects.display(); education.display();
2093bf638f8c6cfbdd399a85e5fbbfa626f23ea5
[ "JavaScript" ]
1
JavaScript
markghsu/frontend-nanodegree-resume
2b0508ae62464a56713780d939de7f7433fd730e
47b9db03b38de25bcbb4e1cbd624dc091755799c
refs/heads/master
<file_sep>"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _Assets = require("./components/Assets"); var _Assets2 = _interopRequireDefault(_Assets); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = _Assets2.default;<file_sep>### Develop ```shell yarn install yarn wattch ``` ### Create this boilerplate: ```shell # For react yarn add react prop-types # For babel transform yarn add --dev babel-cli babel-preset-react-app babel-plugin-transform-decorators-legacy babel-plugin-transform-class-properties babel-plugin-transform-object-rest-spread # TODO: For test ``` Setup `package.json`: Entry point is `dist/index.js` ```json { "main": "dist/index.js", } ``` Scripts ``` { scripts: { ... see package.json for more detail ... } } ``` <file_sep>You can put your helper here
6500560799cce48f9c6dc14e542dd37b40a7a361
[ "JavaScript", "Markdown" ]
3
JavaScript
luatnd/aframe-react-assets
8db25461c978ff0b4ab9002760c5d06f991f9f6f
de7d4e95af0c6dd791deaa84625634dcd548ae73
refs/heads/main
<repo_name>deus2020/codes-tp7<file_sep>/1622847114074_Program.cs  using System; using System.Threading; using System.Data; public class BoundedBuffer { // Complete this class private int ReadData; public BoundedBuffer(){} } class MyProducer { private Random rand = new Random(1); private BoundedBuffer boundedBuffer; private int totalIters; public MyProducer(BoundedBuffer boundedBuffer, int iterations) { this.boundedBuffer = boundedBuffer; totalIters = iterations; } public Thread CreateProducerThread() { return new Thread(new ThreadStart(this.calculate)); } private void calculate() { int iters = 0; do { iters += 1; Thread.Sleep(rand.Next(2000)); //boundedBuffer.WriteData(iters * 4); iters = iters * 4; } while (iters < totalIters); } } class MyConsumer { private Random rand = new Random(2); private BoundedBuffer boundedBuffer; private int totalIters; public MyConsumer(BoundedBuffer boundedBuffer, int iterations) { this.boundedBuffer = boundedBuffer; totalIters = iterations; } public Thread CreateConsumerThread() { return new Thread(new ThreadStart(this.printValues)); } private void printValues() { int iters = 0; double pi=1; do { Thread.Sleep(rand.Next(2000)); //boundedBuffer.ReadData(out pi); pi += pi; System.Console.WriteLine("Value {0} is: {1}", iters, pi.ToString()); iters++; } while (iters < totalIters); System.Console.WriteLine("Done"); } } class MainClass { static void Main(string[] args) { BoundedBuffer boundedBuffer = new BoundedBuffer(); MyProducer prod = new MyProducer(boundedBuffer, 20); Thread producerThread = prod.CreateProducerThread(); MyConsumer cons = new MyConsumer(boundedBuffer, 20); Thread consumerThread = cons.CreateConsumerThread(); producerThread.Start(); consumerThread.Start(); Console.ReadLine(); } }
d3a1b39ca9f2770974f19bba11816673c4dd3a84
[ "C#" ]
1
C#
deus2020/codes-tp7
f16f66302947bd0e7711326fa1e9dd84e61962e9
0d3606c433837fb6f0ebcdd65f067dab13d6c195
refs/heads/main
<file_sep>""" <NAME> ,GeeksForGeeks Originally using C++ """ import sys #print(sys.getrecursionlimit()) sys.setrecursionlimit(15000) #print(sys.getrecursionlimit()) dp = [-1]*1000000 def fib(n): if(n<=1): return n if (dp[n - 1] != -1) : first = dp[n - 1] else: first = fib(n - 1) if (dp[n - 2] != -1) : second = dp[n - 2] else: second = fib(n - 2) dp[n] = first+second #print(dp[n]) return dp[n] n = int(input("Enter the n value: ")) print("Nth term is : ",fib(n))<file_sep>import sys sys.setrecursionlimit(15000) def fact(n): if (n==1): return n else: return(n*fact(n-1)) n=int(input("enter a number: ")) print(fact(n))<file_sep># week2 Practice problems for week 2 including fibonacci and factorial
924038f29dbd837c0abc3800c2354b3e7289143c
[ "Markdown", "Python" ]
3
Python
Bharath-Gopal/week2
18df753d3470e7bc3eae83cf7759e767073e9523
da0be36f770c5c18cceebbb1c345cf4ef7ed63cc
refs/heads/master
<repo_name>xarrondo/API<file_sep>/Api.php <?php function sendTweet($mensaje){ ini_set('display_errors', 1); require_once('TwitterAPIExchange.php'); /** Set access tokens here - see: https://dev.twitter.com/apps/ **/ $settings = array( 'oauth_access_token' => "<KEY>", 'oauth_access_token_secret' => "<KEY>", 'consumer_key' => "DvugPXKQONHmUX6Zw9fiooZhh", 'consumer_secret' => "<KEY>" ); /** URL for REST request, see: https://dev.twitter.com/docs/api/1.1/ **/ $url = 'https://api.twitter.com/1.1/statuses/update.json'; // $url = 'https%3A%2F%2Fapi.twitter.com%2F1.1%2Fstatuses%2Fupdate.json'; $requestMethod = 'POST'; /** POST fields required by the URL above. See relevant docs as above **/ $postfields = array( 'status' => $mensaje, ); /** Perform a POST request and echo the response **/ $twitter = new TwitterAPIExchange($settings); return $twitter->buildOauth($url, $requestMethod)->setPostfields($postfields)->performRequest(); } $mensaje = "Tutorial realizado con éxito en #PHP + #Twitter"; $respuesta = sendTweet($mensaje); $json = json_decode($respuesta); echo '<meta charset="utf-8">'; echo "Tweet Enviado por: ".$json->user->name." (@".$json->user->screen_name.")"; echo "<br>"; echo "Tweet: ".$json->text; echo "<br>"; echo "Tweet ID: ".$json->id_str; echo "<br>"; echo "Fecha Envio: ".$json->created_at; ?> <file_sep>/README.md API === No funciona en localhost
badd5980e43b920c3618863def425959daa4e743
[ "Markdown", "PHP" ]
2
PHP
xarrondo/API
15df76c89e8f544bf4f6c8976238b71cdaae23de
bf79d4f77d702e031f2b1201cc95117c60c283bc
refs/heads/master
<repo_name>asyba/pebble-plex-remote<file_sep>/README.md pebble-plex-remote ================== ![](https://raw.github.com/spangborn/pebble-plex-remote/master/screenshot.png) ##Plex Remote for Pebble - Uses PebbleKitJS from Pebble SDK 2.0 - Configurable from Pebble's smartphone application ##[Demo Video](http://www.youtube.com/watch?v=zWCBPYqwQMY) ###How to Use 1. Install pebble-plex-remote.pbw from [MyPebbleFaces](http://www.mypebblefaces.com/apps/1936/7371/). 2. Tap "Plex Remote" in the Pebble app 3. Enter a Plex Server hostname or IP address (192.168.x.x, or plex-server). 4. Tap "Get Clients" 5. Select a Plex Client to control from the dropdown list. 6. Tap "Save" 7. Enjoy! ###Setup Screenshots ####Selecting a Plex Server ![](http://i.imgur.com/3sDZdg5.png) ####Selecting a Plex Client ![](http://i.imgur.com/0AJyotG.png) ###How to Install $ export PEBBLE_PHONE=<YOUR PHONE'S IP ADDRESS> $ pebble build && pebble install $ pebble logs ###Roadmap 1. Display currently playing media 2. Enable navigation of on-screen menus 3. Implement XBMC integration? <file_sep>/src/plex-remote.c #include <pebble.h> static Window *window; static BitmapLayer *logo_layer; static GBitmap *logo_img; static ActionBarLayer *action_bar; static GBitmap *action_icon_previous; static GBitmap *action_icon_next; static GBitmap *action_icon_playpause; static void send_message(char* message) { DictionaryIterator *iter; app_message_outbox_begin(&iter); Tuplet value = TupletCString(1, message); dict_write_tuplet(iter, &value); app_message_outbox_send(); } static void up_click_handler(ClickRecognizerRef recognizer, void *context) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Previous clicked."); send_message("previous"); } static void down_click_handler(ClickRecognizerRef recognizer, void *context) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Next clicked."); send_message("next"); } static void select_click_handler(ClickRecognizerRef recognizer, void *context) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Play/pause clicked."); send_message("playpause"); } static void click_config_provider(void *context) { window_single_click_subscribe(BUTTON_ID_SELECT, select_click_handler); window_single_click_subscribe(BUTTON_ID_UP, up_click_handler); window_single_click_subscribe(BUTTON_ID_DOWN, down_click_handler); } static void window_load(Window *window) { // Action Bar action_bar = action_bar_layer_create(); action_bar_layer_add_to_window(action_bar, window); action_bar_layer_set_click_config_provider(action_bar, click_config_provider); action_bar_layer_set_icon(action_bar, BUTTON_ID_UP, action_icon_previous); action_bar_layer_set_icon(action_bar, BUTTON_ID_DOWN, action_icon_next); action_bar_layer_set_icon(action_bar, BUTTON_ID_SELECT, action_icon_playpause); // Window Layer *window_layer = window_get_root_layer(window); //GRect bounds = layer_get_bounds(window_layer); // Resources logo_img = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_PLEX_LOGO); logo_layer = bitmap_layer_create(GRect(32,34,80,80)); bitmap_layer_set_bitmap(logo_layer, logo_img); layer_add_child(window_layer, bitmap_layer_get_layer(logo_layer)); } static void window_unload(Window *window) { bitmap_layer_destroy(logo_layer); gbitmap_destroy(logo_img); action_bar_layer_destroy(action_bar); } static void init(void) { action_icon_previous = gbitmap_create_with_resource(RESOURCE_ID_ICON_PREVIOUS); action_icon_next = gbitmap_create_with_resource(RESOURCE_ID_ICON_NEXT); action_icon_playpause = gbitmap_create_with_resource(RESOURCE_ID_ICON_PLAYPAUSE); window = window_create(); window_set_click_config_provider(window, click_config_provider); window_set_window_handlers(window, (WindowHandlers) { .load = window_load, .unload = window_unload, }); const bool animated = true; window_stack_push(window, animated); } static void deinit(void) { window_destroy(window); } int main(void) { init(); APP_LOG(APP_LOG_LEVEL_DEBUG, "Done initializing, pushed window: %p", window); const uint32_t inbound_size = 64; const uint32_t outbound_size = 64; app_message_open(inbound_size, outbound_size); app_event_loop(); deinit(); }
4da55e6add66d9e7c39f06f9a5193d3fc88b5227
[ "Markdown", "C" ]
2
Markdown
asyba/pebble-plex-remote
5f6641785b71cef1aab9c9d384dedde9bbfa5258
ef8b6d0a0a918ca06eb1f4e9b56f296b9b409bfd
refs/heads/master
<file_sep>// JavaScript Document function reCalc() { var income, expenses, liquid, rate, qualify; income = document.getElementById('nettincome').value; expenses = document.getElementById('expenses').value; liquid = income - expenses; rate = document.getElementById('rate').options[document.getElementById('rate').selectedIndex].value; qualify = getMaxLoan(liquid,rate); document.getElementById('qualify').innerHTML = 'R ' + rounding(qualify); document.getElementById('selectedrate').innerHTML = rate; document.getElementById('15yrs').innerHTML = 'R ' + rounding(rePayment(qualify, rate, 15)) + ' pm'; document.getElementById('20yrs').innerHTML = 'R ' + rounding(rePayment(qualify, rate, 20)) + ' pm'; document.getElementById('25yrs').innerHTML = 'R ' + rounding(rePayment(qualify, rate, 25)) + ' pm'; document.getElementById('30yrs').innerHTML = 'R ' + rounding(rePayment(qualify, rate, 30)) + ' pm'; } function getMaxLoan(liquid, rate) { var j, qualify; j = rate/1200; qualify = ((liquid)*0.470054)/(j/(1-(Math.pow((j+1),-(12*20))))); return qualify; } function rePayment(qualify, rate, term) { var j, monthly; j = rate/1200; monthly = qualify * (j/(1-(1/(Math.pow((j+1), (term*12)))))); return monthly; } function rounding(n) { pennies = n * 100 ; pennies = Math.round(pennies) ; strPennies = "" + pennies ; len = strPennies.length ; if(len<=1){ return '0.0'+strPennies; }else if(len<=2){ return "0." + strPennies.substring((len - 2), len); }else if(len<=5){ return strPennies.substring(0, len - 2) + "." + strPennies.substring((len - 2), len); }else if(len<=8){ return strPennies.substring(0, len - 5) + " " + strPennies.substring(len -5, len - 2) + "." + strPennies.substring((len - 2), len); }else if(len<=11){ return strPennies.substring(0, len - 8) + " " + strPennies.substring(len -8, len - 5) + " " + strPennies.substring(len -5, len - 2) + "." + strPennies.substring((len - 2), len); }else{ return strPennies.substring(0, len - 8) + " " + strPennies.substring(len -8, len - 5) + " " + strPennies.substring(len -5, len - 2) + "." + strPennies.substring((len - 2), len); } }
b63e828e85c2bbf6f78000737506303aa9e6c82d
[ "JavaScript" ]
1
JavaScript
tommeintjes/BondcalcV1
7f7ee939d383680e39f7416567b3bd8e321034bf
cf8fb6e16d805a34c16ccb66d4af330aa4170134
refs/heads/master
<repo_name>rchpro/tap-as-a-service<file_sep>/neutron_taas/services/taas/taas_plugin.py # Copyright (C) 2015 Ericsson AB # Copyright (c) 2015 Gigamon # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_config import cfg import oslo_messaging as messaging from neutron.common import rpc as n_rpc from neutron_taas.common import topics from neutron_taas.db import taas_db from neutron_taas.extensions import taas as taas_ex from oslo_log import log as logging LOG = logging.getLogger(__name__) class TaasCallbacks(object): """Currently there are no callbacks to the Taas Plugin.""" def __init__(self, plugin): super(TaasCallbacks, self).__init__() self.plugin = plugin return class TaasAgentApi(object): """RPC calls to agent APIs""" def __init__(self, topic, host): self.host = host target = messaging.Target(topic=topic, version='1.0') self.client = n_rpc.get_client(target) return def create_tap_service(self, context, tap_service, host): LOG.debug("In RPC Call for Create Tap Service: Host=%s, MSG=%s" % (host, tap_service)) cctxt = self.client.prepare(fanout=True) cctxt.cast(context, 'create_tap_service', tap_service=tap_service, host=host) return def create_tap_flow(self, context, tap_flow_msg, host): LOG.debug("In RPC Call for Create Tap Flow: Host=%s, MSG=%s" % (host, tap_flow_msg)) cctxt = self.client.prepare(fanout=True) cctxt.cast(context, 'create_tap_flow', tap_flow_msg=tap_flow_msg, host=host) return def delete_tap_service(self, context, tap_service, host): LOG.debug("In RPC Call for Delete Tap Service: Host=%s, MSG=%s" % (host, tap_service)) cctxt = self.client.prepare(fanout=True) cctxt.cast(context, 'delete_tap_service', tap_service=tap_service, host=host) return def delete_tap_flow(self, context, tap_flow_msg, host): LOG.debug("In RPC Call for Delete Tap Flow: Host=%s, MSG=%s" % (host, tap_flow_msg)) cctxt = self.client.prepare(fanout=True) cctxt.cast(context, 'delete_tap_flow', tap_flow_msg=tap_flow_msg, host=host) return class TaasPlugin(taas_db.Tass_db_Mixin): supported_extension_aliases = ["taas"] path_prefix = "/taas" def __init__(self): LOG.debug("TAAS PLUGIN INITIALIZED") self.endpoints = [TaasCallbacks(self)] self.conn = n_rpc.create_connection() self.conn.create_consumer( topics.TAAS_PLUGIN, self.endpoints, fanout=False) self.conn.consume_in_threads() self.agent_rpc = TaasAgentApi( topics.TAAS_AGENT, cfg.CONF.host ) return def create_tap_service(self, context, tap_service): LOG.debug("create_tap_service() called") t_s = tap_service['tap_service'] tenant_id = t_s['tenant_id'] port_id = t_s['port_id'] # Get port details port = self._get_port_details(context, port_id) # Check if the port is owned by the tenant. if port['tenant_id'] != tenant_id: raise taas_ex.PortDoesNotBelongToTenant() # Extract the host where the port is located host = port['binding:host_id'] if host is not None: LOG.debug("Host on which the port is created = %s" % host) else: LOG.debug("Host could not be found, Port Binding disbaled!") # Create tap service in the db model ts = super(TaasPlugin, self).create_tap_service(context, tap_service) # Get taas id associated with the Tap Service tap_id_association = self.get_tap_id_association( context, tap_service_id=ts['id']) taas_vlan_id = (tap_id_association['taas_id'] + cfg.CONF.taas.vlan_range_start) if taas_vlan_id > cfg.CONF.taas.vlan_range_end: raise taas_ex.TapServiceLimitReached() rpc_msg = {'tap_service': ts, 'taas_id': taas_vlan_id, 'port': port} self.agent_rpc.create_tap_service(context, rpc_msg, host) return ts def delete_tap_service(self, context, id): LOG.debug("delete_tap_service() called") # Get taas id associated with the Tap Service tap_id_association = self.get_tap_id_association( context, tap_service_id=id) ts = self.get_tap_service(context, id) # Get all the tap Flows that are associated with the Tap service # and delete them as well t_f_collection = self.get_tap_flows( context, filters={'tap_service_id': [id]}, fields=['id']) for t_f in t_f_collection: self.delete_tap_flow(context, t_f['id']) # Get the port and the host that it is on port_id = ts['port_id'] port = self._get_port_details(context, port_id) host = port['binding:host_id'] super(TaasPlugin, self).delete_tap_service(context, id) taas_vlan_id = (tap_id_association['taas_id'] + cfg.CONF.taas.vlan_range_start) rpc_msg = {'tap_service': ts, 'taas_id': taas_vlan_id, 'port': port} self.agent_rpc.delete_tap_service(context, rpc_msg, host) return ts def create_tap_flow(self, context, tap_flow): LOG.debug("create_tap_flow() called") t_f = tap_flow['tap_flow'] tenant_id = t_f['tenant_id'] # Check if the tenant id of the source port is the same as the # tenant_id of the tap service we are attaching it to. ts = self.get_tap_service(context, t_f['tap_service_id']) ts_tenant_id = ts['tenant_id'] taas_id = (self.get_tap_id_association( context, tap_service_id=ts['id'])['taas_id'] + cfg.CONF.taas.vlan_range_start) if tenant_id != ts_tenant_id: raise taas_ex.TapServiceNotBelongToTenant() # Extract the host where the source port is located port = self._get_port_details(context, t_f['source_port']) host = port['binding:host_id'] port_mac = port['mac_address'] # create tap flow in the db model tf = super(TaasPlugin, self).create_tap_flow(context, tap_flow) # Send RPC message to both the source port host and # tap service(destination) port host rpc_msg = {'tap_flow': tf, 'port_mac': port_mac, 'taas_id': taas_id, 'port': port} self.agent_rpc.create_tap_flow(context, rpc_msg, host) return tf def delete_tap_flow(self, context, id): LOG.debug("delete_tap_flow() called") tf = self.get_tap_flow(context, id) taas_id = (self.get_tap_id_association( context, tf['tap_service_id'])['taas_id'] + cfg.CONF.taas.vlan_range_start) port = self._get_port_details(context, tf['source_port']) host = port['binding:host_id'] port_mac = port['mac_address'] super(TaasPlugin, self).delete_tap_flow(context, id) # Send RPC message to both the source port host and # tap service(destination) port host rpc_msg = {'tap_flow': tf, 'port_mac': port_mac, 'taas_id': taas_id, 'port': port} self.agent_rpc.delete_tap_flow(context, rpc_msg, host) return tf <file_sep>/neutron_taas/tests/unit/services/taas/test_taas_plugin.py # Copyright (C) 2015 <NAME>. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import contextlib import mock import testtools from oslo_config import cfg from oslo_utils import uuidutils import neutron.common.rpc as n_rpc import neutron.common.utils as n_utils from neutron import context from neutron.tests.unit import testlib_api import neutron_taas.db.taas_db # noqa import neutron_taas.extensions.taas as taas_ext from neutron_taas.services.taas import taas_plugin class TestTaasPlugin(testlib_api.SqlTestCase): def setUp(self): super(TestTaasPlugin, self).setUp() mock.patch.object(n_rpc, 'create_connection', auto_spec=True).start() mock.patch.object(taas_plugin, 'TaasCallbacks', auto_spec=True).start() mock.patch.object(taas_plugin, 'TaasAgentApi', auto_spec=True).start() self._plugin = taas_plugin.TaasPlugin() self._context = context.get_admin_context() self._tenant_id = 'tenant-X' self._network_id = uuidutils.generate_uuid() self._host_id = 'host-A' self._port_id = uuidutils.generate_uuid() self._port_details = { 'tenant_id': self._tenant_id, 'binding:host_id': self._host_id, 'mac_address': n_utils.get_random_mac( 'fa:16:3e:00:00:00'.split(':')), } self._tap_service = { 'tenant_id': self._tenant_id, 'name': 'MyTap', 'description': 'This is my tap service', 'port_id': self._port_id, 'network_id': self._network_id, } self._tap_flow = { 'description': 'This is my tap flow', 'direction': 'BOTH', 'name': 'MyTapFlow', 'source_port': self._port_id, 'tenant_id': self._tenant_id, } @contextlib.contextmanager def tap_service(self): req = { 'tap_service': self._tap_service, } with mock.patch.object(self._plugin, '_get_port_details', return_value=self._port_details): yield self._plugin.create_tap_service(self._context, req) self._tap_service['id'] = mock.ANY expected_msg = { 'tap_service': self._tap_service, 'taas_id': mock.ANY, 'port': self._port_details, } self._plugin.agent_rpc.assert_has_calls([ mock.call.create_tap_service(self._context, expected_msg, self._host_id), ]) @contextlib.contextmanager def tap_flow(self, tap_service, tenant_id=None): self._tap_flow['tap_service_id'] = tap_service if tenant_id is not None: self._tap_flow['tenant_id'] = tenant_id req = { 'tap_flow': self._tap_flow, } with mock.patch.object(self._plugin, '_get_port_details', return_value=self._port_details): yield self._plugin.create_tap_flow(self._context, req) self._tap_flow['id'] = mock.ANY self._tap_service['id'] = mock.ANY expected_msg = { 'tap_flow': self._tap_flow, 'port_mac': self._port_details['mac_address'], 'taas_id': mock.ANY, 'port': self._port_details, } self._plugin.agent_rpc.assert_has_calls([ mock.call.create_tap_flow(self._context, expected_msg, self._host_id), ]) def test_create_tap_service(self): with self.tap_service(): pass def test_create_tap_service_wrong_tenant_id(self): self._port_details['tenant_id'] = 'other-tenant' with testtools.ExpectedException(taas_ext.PortDoesNotBelongToTenant), \ self.tap_service(): pass self.assertEqual([], self._plugin.agent_rpc.mock_calls) def test_create_tap_service_reach_limit(self): cfg.CONF.set_override('vlan_range_end', 3900, 'taas') # same as start with testtools.ExpectedException(taas_ext.TapServiceLimitReached), \ self.tap_service(): pass self.assertEqual([], self._plugin.agent_rpc.mock_calls) def test_delete_tap_service(self): with self.tap_service() as ts: self._plugin.delete_tap_service(self._context, ts['id']) expected_msg = { 'tap_service': self._tap_service, 'taas_id': mock.ANY, 'port': self._port_details, } self._plugin.agent_rpc.assert_has_calls([ mock.call.delete_tap_service(self._context, expected_msg, self._host_id), ]) def test_delete_tap_service_with_flow(self): with self.tap_service() as ts, \ self.tap_flow(tap_service=ts['id']) as tf: self._plugin.delete_tap_service(self._context, ts['id']) expected_msg = { 'tap_service': self._tap_service, 'taas_id': mock.ANY, 'port': self._port_details, } self._plugin.agent_rpc.assert_has_calls([ mock.call.delete_tap_service(self._context, expected_msg, self._host_id), ]) self._tap_flow['id'] = tf['id'] expected_msg = { 'tap_flow': self._tap_flow, 'taas_id': mock.ANY, 'port_mac': self._port_details['mac_address'], 'port': self._port_details, } self._plugin.agent_rpc.assert_has_calls([ mock.call.delete_tap_flow(self._context, expected_msg, self._host_id), ]) def test_delete_tap_service_non_existent(self): with testtools.ExpectedException(taas_ext.TapServiceNotFound): self._plugin.delete_tap_service(self._context, 'non-existent') def test_create_tap_flow(self): with self.tap_service() as ts, self.tap_flow(tap_service=ts['id']): pass def test_create_tap_flow_wrong_tenant_id(self): with self.tap_service() as ts, \ testtools.ExpectedException(taas_ext.TapServiceNotBelongToTenant), \ self.tap_flow(tap_service=ts['id'], tenant_id='other-tenant'): pass def test_delete_tap_flow(self): with self.tap_service() as ts, \ self.tap_flow(tap_service=ts['id']) as tf: self._plugin.delete_tap_flow(self._context, tf['id']) self._tap_flow['id'] = tf['id'] expected_msg = { 'tap_flow': self._tap_flow, 'taas_id': mock.ANY, 'port_mac': self._port_details['mac_address'], 'port': self._port_details, } self._plugin.agent_rpc.assert_has_calls([ mock.call.delete_tap_flow(self._context, expected_msg, self._host_id), ])
a2584f95721ba0b749bbf7c9ac58d83f7765fb78
[ "Python" ]
2
Python
rchpro/tap-as-a-service
fe2d77448da04809ebf1925502923e34327ed080
a4f9ffa93911012a6790cf68d5fe35fb118bbf1e
refs/heads/master
<repo_name>prospectsource/prospectsource.github.io<file_sep>/js/plans-features-react.js var PlayerRegistration = React.createClass({ mixins: [ReactFireMixin], getInitialState: function() { return { prospects: [], planSelection: '', }; }, componentWillMount: function() { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com'); this.bindAsArray(firebaseRef.limitToLast(25), 'prospects'); }, planSelectionChange: function(e) { this.setState({planSelection: e.target.value}); }, removeItem: function(key) { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com'); firebaseRef.child(key).remove(); }, handleSubmit: function(e) { e.preventDefault(); if (this.state.planSelection && this.state.planSelection.trim().length !== 0) { this.firebaseRefs['prospects'].push({ planSelection: this.state.planSelection }); this.setState({ planSelection: '' }); } }, handleButtonClick: function(event) { // Prevent default anchor click behavior event.preventDefault(); // Store hash // Using jQuery's animate() method to add smooth page scroll // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area $('html, body').animate({ scrollTop: $(billing).offset().top - 100 }, 800); }, render: function() { return ( <section className="page"> <form className="text-center" onSubmit={ this.handleSubmit }> <div className="container"> <div className="row"> <div className="col-xs-12"> <div className="header text-center"> <img id="table-logo" src="img/ps-logo-sm.png" className="img-responsive" alt=""/> <h2>Plans & Features</h2> </div> </div> </div> <div className="row"> <div className="col-md-offset-1 col-md-2"> <table id="plans-features-table" className="text-center"> <thead> <tr id="table-header-row"> <th className="features"><h5>Basic</h5> <div className="cost" >Free</div> <div>Showcase & track your recruiting</div></th> </tr> </thead> <tbody> <tr> <td className="" >Showcase Contact Information to College Coaches</td> </tr> <tr> <td className="" >Showcase Athletic Information to College Coaches</td> </tr> <tr> <td className="" >Showcase Academic Information to College Coaches</td> </tr> <tr> <td className="" >Showcase Recruiting Interest To College Coaches</td> </tr> </tbody> <tfoot> <tr> <td className=" background-blue"> <input name="price-choice" type="radio" onChange={this.state.planSelectionChange} value={ this.state.planSelection } value="free" /> <div>Free!</div> </td> </tr> </tfoot> </table> </div> <div className="col-md-2"> <table id="plans-features-table" className="text-center"> <thead> <tr id="table-header-row"> <th className="features"><h5>Plus</h5> <div className="cost" >$60/year</div> <div className="cost-month" >($5/month)</div> <div>Track other recruits and who is following you</div></th> </tr> </thead> <tbody> <tr> <td className="" >Showcase Contact Information to College Coaches</td> </tr> <tr> <td className="" >Showcase Athletic Information to College Coaches</td> </tr> <tr> <td className="" >Showcase Academic Information to College Coaches</td> </tr> <tr> <td className="" >Showcase Recruiting Interest To College Coaches</td> </tr> <tr> <td className=" background-light-gray" >See Who Is Recruiting Other Prospects</td> </tr> <tr> <td className=" background-light-gray" >Store Unlimited Game Film</td> </tr> <tr> <td className=" background-light-gray" >See Coach Views On Profile</td> </tr> <tr> <td className=" background-light-gray" >See Coach Notifications Set On Your Profile</td> </tr> </tbody> <tfoot> <tr> <td className=" background-blue"> <input name="price-choice" type="radio" onChange={this.state.planSelectionChange} value={ this.state.planSelection } value="5.00" /> <div>Monthly</div> <div>$5.00/month</div> </td> </tr> <tr> <td className=" background-blue"> <input name="price-choice" type="radio" onChange={this.state.planSelectionChange} value={ this.state.planSelection } value="54.00"/> <div>Yearly</div> <div>$54.00</div> <div>(10% off)</div> </td> </tr> </tfoot> </table> </div> <div className="col-md-2"> <table id="plans-features-table" className="text-center"> <thead> <tr id="table-header-row"> <th className="features"><h5>Premium 1</h5> <div className="cost">$160/year</div> <div className="cost-month" >($13.33/month)</div> <div>Let us send out your highlight video</div></th> </tr> </thead> <tbody> <tr> <td className="" >Showcase Contact Information to College Coaches</td> </tr> <tr> <td className="" >Showcase Athletic Information to College Coaches</td> </tr> <tr> <td className="" >Showcase Academic Information to College Coaches</td> </tr> <tr> <td className="" >Showcase Recruiting Interest To College Coaches</td> </tr> <tr> <td className=" background-light-gray" >See Who Is Recruiting Other Prospects</td> </tr> <tr> <td className=" background-light-gray" >Store Unlimited Game Film</td> </tr> <tr> <td className=" background-light-gray" >See Coach Views On Profile</td> </tr> <tr> <td className=" background-light-gray" >See Coach Notifications Set On Your Profile</td> </tr> <tr> <td className=" background-gray" >Highlight Distributed To College Coaches</td> </tr> </tbody> <tfoot> <tr> <td className=" background-blue"> <input name="price-choice" type="radio" onChange={this.state.planSelectionChange} value={ this.state.planSelection } value="13.33" /> <div>Monthly</div> <div>$13.33/month</div> </td> </tr> <tr> <td className=" background-blue"> <input name="price-choice" type="radio" onChange={this.state.planSelectionChange} value={ this.state.planSelection } value="144.00"/> <div>Yearly</div> <div>$144.00</div> <div>(10% off)</div> </td> </tr> </tfoot> </table> </div> <div className="col-md-2"> <table id="plans-features-table" className="text-center"> <thead> <tr id="table-header-row"> <th className="features"><h5>Premium 2</h5> <div className="cost" >$260/year</div> <div className="cost-month" >($21.67/month)</div> <div>Let us create and send one video/year</div></th> </tr> </thead> <tbody> <tr> <td className="" >Showcase Contact Information to College Coaches</td> </tr> <tr> <td className="" >Showcase Athletic Information to College Coaches</td> </tr> <tr> <td className="" >Showcase Academic Information to College Coaches</td> </tr> <tr> <td className="" >Showcase Recruiting Interest To College Coaches</td> </tr> <tr> <td className=" background-light-gray" >See Who Is Recruiting Other Prospects</td> </tr> <tr> <td className=" background-light-gray" >Store Unlimited Game Film</td> </tr> <tr> <td className=" background-light-gray" >See Coach Views On Profile</td> </tr> <tr> <td className=" background-light-gray" >See Coach Notifications Set On Your Profile</td> </tr> <tr> <td className=" background-gray" >Highlight Distributed To College Coaches</td> </tr> <tr> <td className=" background-blue" >Highlight Produced & Distributed To College Coaches (Once)</td> </tr> </tbody> <tfoot> <tr> <td className=" background-blue"> <input name="price-choice" type="radio" onChange={this.handleUserInput} value={ this.state.planSelection } /> <div>Monthly</div> <div>$21.67/month</div> </td> </tr> <tr> <td className=" background-blue"> <input name="price-choice" type="radio" onChange={this.handleUserInput} value={ this.state.planSelection } /> <div>Yearly</div> <div>$234.00</div> <div>(10% off)</div> </td> </tr> </tfoot> </table> </div> <div className="col-md-2"> <table id="plans-features-table" className="text-center"> <thead> <tr id="table-header-row"> <th className="features"><h5>Premium 3</h5> <div className="cost" >$460/year</div> <div className="cost-month" >($38.33/month)</div> <div>Let us create and send two video/year</div></th> </tr> </thead> <tbody> <tr> <td className="" >Showcase Contact Information to College Coaches</td> </tr> <tr> <td className="" >Showcase Athletic Information to College Coaches</td> </tr> <tr> <td className="" >Showcase Academic Information to College Coaches</td> </tr> <tr> <td className="" >Showcase Recruiting Interest To College Coaches</td> </tr> <tr> <td className=" background-light-gray" >See Who Is Recruiting Other Prospects</td> </tr> <tr> <td className=" background-light-gray" >Store Unlimited Game Film</td> </tr> <tr> <td className=" background-light-gray" >See Coach Views On Profile</td> </tr> <tr> <td className=" background-light-gray" >See Coach Notifications Set On Your Profile</td> </tr> <tr> <td className=" background-gray" >Highlight Distributed To College Coaches</td> </tr> <tr> <td className=" background-blue" >Highlight Produced & Distributed To College Coaches (Once)</td> </tr> <tr> <td className=" background-blue" >Highlight Produced & Distributed To College Coaches (Twice)</td> </tr> </tbody> <tfoot> <tr> <td className=" background-blue"> <input name="price-choice" type="radio" onChange={this.handleUserInput} value={ this.state.planSelection } /> <div>Monthly</div> <div>$38.33/month</div> </td> </tr> <tr> <td className=" background-blue"> <input name="price-choice" type="radio" onChange={this.handleUserInput} value={ this.state.planSelection } /> <div>Yearly</div> <div>$414.00</div> <div>(10% off)</div> </td> </tr> </tfoot> </table> </div> </div> </div> <button className="btn btn-default btn-large">To Billing</button> </form> </section> ); } }); ReactDOM.render(<PlayerRegistration />, document.getElementById('plansFeatures'));<file_sep>/js/club-invite-prospects-react.js var ClubInviteProspects = React.createClass({ mixins: [ReactFireMixin], getInitialState: function() { return { items: [], text: '' }; }, componentWillMount: function() { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com'); this.bindAsArray(firebaseRef.limitToLast(25), 'prospects'); }, onChange: function(e) { this.setState({text: e.target.value}); }, onChange2: function(e) { this.setState({text2: e.target.value}); }, onChange3: function(e) { this.setState({text3: e.target.value}); }, removeItem: function(key) { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com'); firebaseRef.child(key).remove(); }, handleSubmit: function(e) { e.preventDefault(); if (this.state.text && this.state.text.trim().length !== 0) { this.firebaseRefs['prospects'].push({ name: this.state.text, position: this.state.text2, // "name:" changes the input attribute category height: this.state.text3 }); this.setState({ name: '', position: '', height: '' }); } this.state.text = String.Empty; this.state.text2 = String.Empty; this.state.text3 = String.Empty; }, render: function() { return ( <section className="page"> <form onSubmit={ this.handleSubmit }> <div className="container"> <div className="row"> <div className="col-sm-12"> <h2 id="congratulations" className="text-center" >Congratulations!</h2> <h3 className="text-center" >You have successfully created your program profile!</h3> <p>You are now ready to invite your prospects to join our service. At any time, you may access your prospects recruiting information from your program dashboard. </p> </div> </div> </div> <button className="btn btn-default btn-large center-button program-button background-light-gray"><h2>Email invite system</h2></button> </form> </section> ); } }); ReactDOM.render(<ClubInviteProspects />, document.getElementById('club-invite-prospects')); <file_sep>/js/username-password-react.js var UsernamePassword = React.createClass({ mixins: [ReactFireMixin], getInitialState: function() { return { items: [], text: '' }; }, componentWillMount: function() { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com/players/'); this.bindAsArray(firebaseRef.limitToLast(25), 'items'); }, onChange: function(e) { this.setState({text: e.target.value}); }, onChange2: function(e) { this.setState({text2: e.target.value}); }, onChange3: function(e) { this.setState({text3: e.target.value}); }, removeItem: function(key) { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com/players/'); firebaseRef.child(key).remove(); }, handleSubmit: function(e) { e.preventDefault(); if (this.state.text && this.state.text.trim().length !== 0) { this.firebaseRefs['items'].push({ name: this.state.text, position: this.state.text2, // "name:" changes the input attribute category height: this.state.text3 }); this.setState({ name: '', position: '', height: '' }); } this.state.text = String.Empty; this.state.text2 = String.Empty; this.state.text3 = String.Empty; }, render: function() { return ( <section className="page"> <form onSubmit={ this.handleSubmit }> <div className="container"> <div className="row"> <div className="col-sm-4"> <div className="timeline-image1 background-blue"> <h2>1</h2> </div> <h5 className="timeline-heading1">CREATE ACCOUNT</h5> </div> <div className="col-sm-4"> <div className="timeline-image2 background-gray"> <h2>2</h2> </div> <h5 className="timeline-heading2">GENERAL INFORMATION</h5> </div> <div className="col-sm-4"> <div className="timeline-image3 background-gray"> <h2>3</h2> </div> <h5 className="timeline-heading3">INVITE PROSPECTS</h5> </div> </div> <div className="row"> <div className="col-sm-3"> <div id="club-admin" className="background-blue"> <h5>AAU PROGRAM</h5> </div> </div> <div className="col-sm-9"> <div>CREATE USERNAME <input onChange={ this.onChange11 } value={ this.state.text11 } /></div> <div>CREATE PASSWORD <input onChange={ this.onChange12 } value={ this.state.text12 } /></div> </div> </div> </div> <button className="btn btn-default btn-large center-button">NEXT</button> </form> </section> ); } }); ReactDOM.render(<UsernamePassword />, document.getElementById('username-password'));<file_sep>/js/marketing-service-react.js var MarketingServiceAd = React.createClass({ render: function() { var _this = this; var createItem = function(prospect, index) { return ( <div id="marketing-confirm" className="marketing-confirm-container text-center"> <div className="marketing-confirm background-light-gray"> <h4>Thanks for submitting your highlight video!</h4> <p className="text-left" >Thanks for submitting a highlight video. Our team will post this video to our YouTube channel and/or distribute it directly to college coaches within your rating. If you only submitted your Hudl highlight URL, we will send this directly to college coaches and push them towards your Hudl profile. </p> <p className="text-left">Your CC on file will be charged accordingly for this service.</p> </div> </div> ); }; return <ul className="prospect-list list-unstyled">{ this.props.prospects.map(createItem) }</ul>; } }); var MarketingService = React.createClass({ mixins: [ReactFireMixin], getInitialState: function() { return { items: [], text: '' }; }, componentWillMount: function() { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com/prospects'); this.bindAsArray(firebaseRef.limitToLast(25), 'prospects'); }, onChange: function(e) { this.setState({text: e.target.value}); }, onChange2: function(e) { this.setState({text2: e.target.value}); }, onChange3: function(e) { this.setState({text3: e.target.value}); }, removeItem: function(key) { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com'); firebaseRef.child(key).remove(); }, handleMarketingClick: function(event) { document.getElementById("marketing-confirm").style.display='block'; }, handleSubmit: function(e) { e.preventDefault(); if (this.state.text && this.state.text.trim().length !== 0) { this.firebaseRefs['prospects'].push({ name: this.state.text, position: this.state.text2, // "name:" changes the input attribute category height: this.state.text3 }); this.setState({ name: '', position: '', height: '' }); } this.state.text = String.Empty; this.state.text2 = String.Empty; this.state.text3 = String.Empty; }, render: function() { return ( <section className=""> <div className="container"> <div className="row"> <div className="col-sm-4 col-md-3"> <div id="video-description" className="panel-container"> <div className="text-center" ><h3>Marketing Service</h3></div> <p id="video-paragraph" >When you upload your highlight video to our Premium Marketing Service, we will send it out to coaches for you!</p> </div> </div> <div className="col-sm-8 col-md-9"> <div className="prospect-container"> <ul className="video-upload-container list-unstyled"> <li>Upload Highlight Video<input className="custom-file-input" type="file" name="video" accept="video/*" /></li> <li>Hudl Highlight URL<input className="custom-file-input" type="text" name="hudl-url" /></li> </ul> <button className="btn btn-default btn-large center-button" onClick={this.handleMarketingClick}>Submit Marketing Order</button> </div> </div> </div> </div> <MarketingServiceAd prospects={this.state.prospects} /> </section> ); } }); ReactDOM.render(<MarketingService/>, document.getElementById('marketing-service')); <file_sep>/js/profile-view-react.js var SchoolRecruitingSummary = React.createClass({ render: function() { var _this = this; var createItem = function(prospect, index) { return ( <div id="school-summary" className="recruit-update-container text-center"> <u><h3>Recruiting Letter</h3></u> <input type="text"/><div className="btn-default search">Search School</div> <div className="letter-attributes background-light-gray"> <ul className=""> <li><input type="checkbox" /><span>Mens</span></li> <li><input type="checkbox" /><span>Womens</span></li> </ul> <label htmlFor="sel1"></label> <select id="sel1" className="form-control standalone" type="select" label="Select" placeholder="select"> <option value="NCAA D1 V">NCAA D1 V</option> <option value="NCAA D2 V">NCAA D2 V</option> <option value="NCAA D3 V">NCAA D3 V</option> <option value="NCAA NAIA V">NCAA NAIA V</option> </select> </div> </div> ); }; return <ul className="prospect-list list-unstyled">{ this.props.prospects.map(createItem) }</ul>; } }); var PlayerPic = React.createClass({ render: function() { return ( <div> <h3>PLAYER PIC</h3> </div> ); } }); var PlayerProfileBasics = React.createClass({ render: function() { var _this = this; var createItem = function(item, index) { return ( <div id="profile-basics" key={ index }> <h3>{ item.first} {item.last} ({ item.grade })</h3> <div><h4>Position:</h4> { item.position}</div> <div><h4>Height:</h4> { item.height}</div> <div><h4>City/State/Zip:</h4> { item.cityStateZip}</div> </div> ); }; return <div>{ this.props.prospects.map(createItem) }</div>; } }); var PlayerProfileContactInfo = React.createClass({ render: function() { var _this = this; var createInfo = function(item, index) { return ( <div id="profile-contact-info" key={ index }> <h3>Contact Information</h3> <div><h4>Phone:</h4> { item.phone}</div> <div><h4>Email:</h4> { item.email}</div> <div><h4>AAU Coach Name:</h4> { item.aauCoach}</div> <div><h4>AAU Coach Email:</h4> { item.aauEmail}</div> <div><h4>AAU Coach Phone:</h4> { item.aauPhone}</div> <div><h4>HS Coach Name:</h4> {item.hsCoach}</div> <div><h4>HS Coach Email:</h4> { item.hsEmail}</div> </div> ); }; return <div>{ this.props.prospects.map(createInfo) }</div>; } }); var PlayerProfileAthleticInfo = React.createClass({ render: function() { var _this = this; var createInfo = function(item, index) { return ( <div id="profile-athletic-info" key={ index }> <h3>Athletic Information</h3> <div><h4>Grade/Class:</h4> { item.grade}</div> <div><h4>Height:</h4> { item.height}</div> <div><h4>Weight:</h4> { item.weight}</div> <div><h4>Vertical Jump:</h4> { item.vert}</div> <div><h4>Position:</h4> { item.position}</div> <div><h4>AAU Program:</h4> {item.program}</div> <div><h4>AAU Jersey:</h4> { item.jersey}</div> <div><h4>High School:</h4> { item.school}</div> <div><h4>HUDL Profile:</h4> { item.hudl}</div> </div> ); }; return <div>{ this.props.prospects.map(createInfo) }</div>; } }); var PlayerProfileAcademicInfo = React.createClass({ render: function() { var _this = this; var createInfo = function(item, index) { return ( <div id="profile-academic-info" key={ index }> <h3>Academic Information</h3> <div><h4>GPA:</h4> { item.gpa}</div> <div><h4>ACT:</h4> { item.act}</div> <div><h4>Class Rank:</h4> { item.classRank}</div> </div> ); }; return <div>{ this.props.prospects.map(createInfo) }</div>; } }); var PlayerRecruitingInterest = React.createClass({ render: function() { return ( <div id="player-recruiting-interest" className=""> <ul className="prospect-categories list-inline"> <li className="cat-btn background-blue">D1</li> <li className="cat-btn background-blue">D2</li> <li className="cat-btn background-blue">D3</li> <li className="cat-btn background-blue">NAIA</li> <li className="cat-btn background-blue">JUCO</li> </ul> <h2 id="prospect-interest" className="text-center" >Recruiting Interest</h2> <div id="recruiting-interest-cats"> <ul> <li className="btn btn-default">High Major</li> <li className="btn btn-default">High Major - / Mid-Major +</li> <li className="btn btn-default">Mid-Major</li> <li className="btn btn-default">Mid-Major - / Low Major +</li> <li className="btn btn-default">Low Major</li> </ul> </div> <div id="recruiting-activity-feed" > <RecruitingActivityFeed prospects={this.props.prospects} /> </div> </div> ); } }); var RecruitingActivityFeed = React.createClass({ handleSummaryClick: function(event) { document.getElementById('school-summary').style.display='block'; }, render: function() { var createItem = function(prospect, index) { return ( <ul className="prospect-activity background-light-gray list-inline" onClick={this.handleSummaryClick} key={ index }> <li className="prospect-update"><i>{prospect.first}</i> Southwest Minnesota</li> </ul> ); }; return <ul className="prospect-list list-unstyled">{ this.props.prospects.map(createItem) }</ul>; } }); var CollegeRecruitingSummary = React.createClass({ render: function() { var _this = this; var createItem = function(prospect, index) { return ( <div id="marketing-add" className="marketing-add-container text-center"> <u><h3>Marketing Service</h3></u> <div className="marketing-attributes background-light-gray"> <ul className="list-inline"> <li><input type="checkbox" /><span>Click here if you want to add our marketing service to your cart (send video directly to coaches)</span></li> </ul> <h4>Thanks for submitting your game film!</h4> <p className="text-left" >Our team will take these files and create a highlight video and make game film available upon request for interested college coaches. You will receive a notification when your video is complete.</p> <p className="text-left">Your CC on file will be charged accordingly for this service. You will be charged $100 for the video service and an additional $100 IF you clicked above to include our marketing service.</p> </div> </div> ); }; return <ul className="prospect-list list-unstyled">{ this.props.prospects.map(createItem) }</ul>; } }); var ProfileViewPage = React.createClass ({ mixins: [ReactFireMixin], componentWillMount: function() { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com/prospects'); this.bindAsArray(firebaseRef.limitToLast(6), 'prospects'); }, handleContactClick: function(event) { document.getElementById('profile-contact-info').style.display='block'; document.getElementById('profile-athletic-info').style.display='none'; document.getElementById('profile-academic-info').style.display='none'; document.getElementById('player-recruiting-interest').style.display='none'; }, handleAthleticClick: function(event) { document.getElementById('profile-contact-info').style.display='none'; document.getElementById('profile-athletic-info').style.display='block'; document.getElementById('profile-academic-info').style.display='none'; document.getElementById('player-recruiting-interest').style.display='none'; }, handleAcademicClick: function(event) { document.getElementById('profile-contact-info').style.display='none'; document.getElementById('profile-athletic-info').style.display='none'; document.getElementById('profile-academic-info').style.display='block'; document.getElementById('player-recruiting-interest').style.display='none'; }, handleRecruitingClick: function(event) { document.getElementById('profile-contact-info').style.display='none'; document.getElementById('profile-athletic-info').style.display='none'; document.getElementById('profile-academic-info').style.display='none'; document.getElementById('player-recruiting-interest').style.display='block'; }, render: function() { return ( <section id="profile" className="page"> <div className="container"> <div id="profile-top-row" className="row profile-top-row"> <div className="col-sm-3"> <div id="profile-picture" className="background-blue"> <div><PlayerPic prospects={this.state.prospects} /></div> </div> </div> <div className="col-sm-6"> <div id="" className=""> <PlayerProfileBasics prospects={ this.state.prospects } /> </div> </div> <div className="col-sm-3"> <div id="notifications" className="background-blue"> <h5>add to notifications</h5> </div> </div> </div> <div className="row"> <div className="col-sm-3"> <div id="club-logo" className="background-blue"> <h5>CLUB LOGO</h5> </div> <div id="" className="data-cat-btn background-gray" onClick={this.handleContactClick}> <h5>Contact Information</h5> </div> <div id="" className="data-cat-btn background-gray" onClick={this.handleAthleticClick}> <h5>Athletic Information</h5> </div> <div id="" className="data-cat-btn background-gray" onClick={this.handleAcademicClick}> <h5>Academic Information</h5> </div> <div id="" className="data-cat-btn background-blue" onClick={this.handleRecruitingClick}> <h5>Recruiting Interest</h5> </div> </div> <div id="athlete-info-container" className="col-sm-9"> <div> <PlayerProfileContactInfo prospects={ this.state.prospects }/> <PlayerProfileAthleticInfo prospects={ this.state.prospects }/> <PlayerProfileAcademicInfo prospects={ this.state.prospects }/> <PlayerRecruitingInterest prospects={ this.state.prospects }/> </div> </div> </div> </div> <SchoolRecruitingSummary prospects={this.state.prospects}/> </section> ); } }); ReactDOM.render(<ProfileViewPage />, document.getElementById('profile-view-page') );<file_sep>/_site/README.md # prospectsource Prospect Source Website <file_sep>/js/video-service-react.js var MarketingServiceAdd = React.createClass({ render: function() { var _this = this; var createItem = function(prospect, index) { return ( <div id="marketing-add" className="marketing-add-container text-center"> <u><h3>Marketing Service</h3></u> <div className="marketing-attributes background-light-gray"> <ul className="list-inline"> <li><input type="checkbox" /><span>Click here if you want to add our marketing service to your cart (send video directly to coaches)</span></li> </ul> <h4>Thanks for submitting your game film!</h4> <p className="text-left" >Our team will take these files and create a highlight video and make game film available upon request for interested college coaches. You will receive a notification when your video is complete.</p> <p className="text-left">Your CC on file will be charged accordingly for this service. You will be charged $100 for the video service and an additional $100 IF you clicked above to include our marketing service.</p> </div> </div> ); }; return <ul className="prospect-list list-unstyled">{ this.props.prospects.map(createItem) }</ul>; } }); var VideoService = React.createClass({ mixins: [ReactFireMixin], getInitialState: function() { return { items: [], text: '' }; }, componentWillMount: function() { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com/prospects'); this.bindAsArray(firebaseRef.limitToLast(25), 'prospects'); }, onChange: function(e) { this.setState({text: e.target.value}); }, onChange2: function(e) { this.setState({text2: e.target.value}); }, onChange3: function(e) { this.setState({text3: e.target.value}); }, removeItem: function(key) { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com'); firebaseRef.child(key).remove(); }, handleVideoClick: function(event) { document.getElementById("marketing-add").style.display='block'; }, handleSubmit: function(e) { e.preventDefault(); if (this.state.text && this.state.text.trim().length !== 0) { this.firebaseRefs['prospects'].push({ name: this.state.text, position: this.state.text2, // "name:" changes the input attribute category height: this.state.text3 }); this.setState({ name: '', position: '', height: '' }); } this.state.text = String.Empty; this.state.text2 = String.Empty; this.state.text3 = String.Empty; }, render: function() { return ( <section className=""> <div className="container"> <div className="row"> <div className="col-sm-4 col-md-3"> <div id="video-description" className="panel-container"> <div className="text-center" ><h3>Premium Video Service</h3></div> <p id="video-paragraph" >When you subscribe to our Premium Video Service, all you have to do is upload your video, and we will take it from there!</p> </div> </div> <div className="col-sm-8 col-md-9"> <div className="prospect-container"> <button className="btn btn-default btn-large center-button background-light-gray"><h5>View Uploaded Video Files</h5></button> <ul className="video-upload-container list-unstyled"> <li>Upload Video<input className="custom-file-input" type="file" name="video" accept="video/*" /></li> <li>Upload Video<input className="custom-file-input" type="file" name="video" accept="video/*" /></li> <li>Upload Video<input className="custom-file-input" type="file" name="video" accept="video/*" /></li> <li>Upload Video<input className="custom-file-input" type="file" name="video" accept="video/*" /></li> <li>Upload Video<input className="custom-file-input" type="file" name="video" accept="video/*" /></li> </ul> <button className="btn btn-default btn-large center-button" onClick={this.handleVideoClick}>Submit Video Order</button> </div> </div> </div> </div> <MarketingServiceAdd prospects={this.state.prospects} /> </section> ); } }); ReactDOM.render(<VideoService/>, document.getElementById('video-service')); <file_sep>/js/select-club-react.js /** @jsx React.DOM */ var TodoList3 = React.createClass({ render: function() { var _this = this; var createItem = function(item, index) { return ( <li key={ index }> <div>Name: { item.name /**this ".name" changes the attribute displayed in the todo list */ }</div> <div>Position: { item.position }</div> <div>Height: { item.height }</div> <div><span onClick={ _this.props.removeItem.bind(null, item['.key']) } style={{ color: 'red', marginLeft: '10px', cursor: 'pointer' }}> Delete Player </span> </div> </li> ); }; return <ul>{ this.props.items.map(createItem) }</ul>; } }); var TodoApp3 = React.createClass({ mixins: [ReactFireMixin], getInitialState: function() { return { items: [], text: '' }; }, componentWillMount: function() { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com/'); this.bindAsArray(firebaseRef.limitToLast(25), 'items'); }, onChange: function(e) { this.setState({aauClub: e.target.value}); }, usernameChange: function(e) { this.setState({username: e.target.value}); }, passwordChange: function(e) { this.setState({password: e.target.value}); }, handleSubmit: function(e) { e.preventDefault(); if (this.state.username && this.state.username.trim().length !== 0) { this.firebaseRefs['prospects'].push({ aauClub: this.state.aauClub, username: this.state.username, // "name:" changes the input attribute category password: <PASSWORD> }); this.setState({ aauClub: '', username: '', password: '' }); } this.state.aauClub = String.Empty; this.state.username = String.Empty; this.state.password = String.Empty; }, render: function() { return ( <section className="page"> <form onSubmit={ this.handleSubmit }> <div className="container"> <div className="row"> <div className="col-sm-4"> <div className="timeline-image1 background-blue"> <h2>1</h2> </div> <h5 className="timeline-heading1">SELECT CLUB</h5> </div> <div className="col-sm-4"> <div className="timeline-image2 background-gray"> <h2>2</h2> </div> <h5 className="timeline-heading2">GENERAL INFORMATION</h5> </div> <div className="col-sm-4"> <div className="timeline-image3 background-gray"> <h2>3</h2> </div> <h5 className="timeline-heading3">BILLING</h5> </div> </div> <div className="row"> <div className="col-sm-3"> <div id="aau-prospect" className="background-blue"> <h5>AAU PROSPECT</h5> </div> </div> <div className="col-sm-9"> <label htmlFor="aau-club">Select Your AAU Club</label> <select onChange={ this.usernameChange } id="aau-club" name="aau-club" className="form-control standalone" type="select" label="Select" placeholder="select"> <option value="Kingdom Hoops">Kingdom Hoops</option> <option value="Rusty's Rascals">Rustys Rascals</option> <option value="McCall MadMen">McCall MadMen</option> <option value="<NAME>ls">Maschoff Monsters</option> </select> </div> <div className="col-sm-offset-3 col-sm-9"> <div>CREATE USERNAME <input onChange={ this.usernameChange } value={ this.state.username } /></div> <div>CREATE PASSWORD <input onChange={ this.onChange12 } value={ this.state.password } /></div> </div> </div> </div> <button onClick={this.handleButtonClick} className="btn btn-default btn-large center-button">NEXT</button> </form> </section> ); } }); ReactDOM.render(<TodoApp3 />, document.getElementById('selectClub'));<file_sep>/js/angularfireupload.js var refImg = new Firebase("https://sweltering-fire-7944.firebaseio.com/images/" + $rootScope.authData.uid); var ImgObj = $firebaseObject(refImg); function saveimage(e1) { var filename = e1.target.files[0]; var fr = new FileReader(); fr.onload = function (res) { $scope.image = res.target.result; ImgObj.image = res.target.result; ImgObj.$save().then(function (val) { }, function (error) { console.log("ERROR", error); }) }; fr.readAsDataURL(filename); } document.getElementById("file-upload").addEventListener('change', saveimage, false); this.loadimage = function () { ImgObj.$loaded().then(function (obj) { $scope.profileImage = obj.image; console.log("loaded", $scope.profileImage); document.getElementById("profileImage").src = obj.image; }, function (error) { console.log("ERROR", error); }); }; this.loadimage();<file_sep>/react-stack/src/components/ProspectRegistration.jsx import React from 'react'; import MessageList from './MessageList.jsx'; import ChannelList from './ChannelList.jsx'; import MessageBox from './MessageBox.jsx'; class ProspectRegistration extends React.Component { render(){ return ( <div> <section className="page"> <div className="container"> <div className="row"> <div className="col-xs-12"> <div className="header text-center"> <h2>Prospect Registration</h2> </div> </div> </div> <div className="row"> <div className="col-sm-3"> <div id="aau-prospect" className="background-blue"> <h5>AAU PROSPECT</h5> </div> </div> <div className="col-sm-9 receive"> <h5><b>RECEIVE:</b> EVALUATION / RECRUITING MANUAL / ACCESS TO PREMIUM SERVICES<em> - MONTHLY FEE: $5.00 (FIRST 6 MONTHS FREE)</em></h5> </div> </div> </div> <form className="text-center" onSubmit={ this.handleSubmit }> <a onClick={this.handleButtonClick} className="btn btn-default btn-large">Click To Register</a> </form> </section> </div> ); } } export default ProspectRegistration; <file_sep>/js/prospect-form-submission-handler.js // get all data in form and return object function getFormData() { var data = { first : document.getElementById("first").value, last : document.getElementById("last").value, gender: document.getElementById("gender").value, year : document.getElementById("year").value, email : document.getElementById("email").value, phone : document.getElementById("phone").value, school : document.getElementById("school").value, club : document.getElementById("club").value, question: document.getElementById("question").value } console.log(data); return data; } function handleFormSubmit(event) { // handles form submit withtout any jquery event.preventDefault(); // we are submitting via xhr below var data = getFormData(); // get the values submitted in the form var url = event.target.action; // var xhr = new XMLHttpRequest(); xhr.open('POST', url); // xhr.withCredentials = true; xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onreadystatechange = function() { console.log( xhr.status, xhr.statusText ) console.log(xhr.responseText); document.getElementById('gform').style.display = 'none'; // hide form document.getElementById('thankyou_message').style.display = 'block'; return; }; // url encode form data for sending as post data var encoded = Object.keys(data).map(function(k) { return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) }).join('&') xhr.send(encoded); } function loaded() { console.log('contact form submission handler loaded successfully'); // bind to the submit event of our form var form = document.getElementById('gform'); form.addEventListener("submit", handleFormSubmit, false); }; document.addEventListener('DOMContentLoaded', loaded, false);<file_sep>/js/player-registration-react.js /** @jsx React.DOM */ var PlayerRegistration = React.createClass({ mixins: [ReactFireMixin], getInitialState: function() { return { items: [], text: '' }; }, componentWillMount: function() { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com/players/'); this.bindAsArray(firebaseRef.limitToLast(25), 'items'); }, onChange: function(e) { this.setState({text: e.target.value}); }, onChange2: function(e) { this.setState({text2: e.target.value}); }, onChange3: function(e) { this.setState({text3: e.target.value}); }, removeItem: function(key) { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com/players/'); firebaseRef.child(key).remove(); }, handleButtonClick: function(event) { // Prevent default anchor click behavior event.preventDefault(); // Store hash // Using jQuery's animate() method to add smooth page scroll // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area $('html, body').animate({ scrollTop: $(selectClub).offset().top - 100 }, 800); }, render: function() { return ( <section className="page"> <div className="container"> <div className="row"> <div className="col-xs-12"> <div className="header text-center"> <h2>Prospect Registration</h2> </div> </div> </div> <div className="row"> <div className="col-sm-3"> <div id="aau-prospect" className="background-blue"> <h5>AAU PROSPECT</h5> </div> </div> <div className="col-sm-9 receive"> <h5><b>RECEIVE:</b> EVALUATION / RECRUITING MANUAL / ACCESS TO PREMIUM SERVICES<em> - MONTHLY FEE: $5.00 (FIRST 6 MONTHS FREE)</em></h5> </div> </div> </div> <form className="text-center" onSubmit={ this.handleSubmit }> <a onClick={this.handleButtonClick} className="btn btn-default btn-large">Click To Register</a> </form> </section> ); } }); ReactDOM.render(<PlayerRegistration />, document.getElementById('playerRegistration'));<file_sep>/js/club-admin-registration-react.js var ClubAdminRegistration = React.createClass({ mixins: [ReactFireMixin], getInitialState: function() { return { items: [], text: '' }; }, componentWillMount: function() { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com/players/'); this.bindAsArray(firebaseRef.limitToLast(25), 'items'); }, onChange: function(e) { this.setState({text: e.target.value}); }, onChange2: function(e) { this.setState({text2: e.target.value}); }, onChange3: function(e) { this.setState({text3: e.target.value}); }, removeItem: function(key) { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com/players/'); firebaseRef.child(key).remove(); }, handleSubmit: function(e) { e.preventDefault(); if (this.state.text && this.state.text.trim().length !== 0) { this.firebaseRefs['items'].push({ name: this.state.text, position: this.state.text2, // "name:" changes the input attribute category height: this.state.text3 }); this.setState({ name: '', position: '', height: '' }); } this.state.text = String.Empty; this.state.text2 = String.Empty; this.state.text3 = String.Empty; }, render: function() { return ( <section className="page"> <div className="container"> <div className="row"> <div className="col-xs-12"> <div className="header text-center"> <h2>Program Registration</h2> </div> </div> </div> <div className="row"> <div className="col-sm-3"> <div id="club-admin" className="background-blue"> <h5>AAU PROGRAM</h5> </div> </div> <div className="col-sm-9 receive text-center"> <h5>OFFER SERVICE AND RECRUITING RESOURCES TO AAU PROSPECTS</h5> </div> </div> </div> <form className="text-center" onSubmit={ this.handleSubmit }> <button className="btn btn-default btn-large">Register Your Club (FREE)</button> </form> </section> ); } }); ReactDOM.render(<ClubAdminRegistration />, document.getElementById('club-admin-registration'));<file_sep>/js/unused-ps-components-react.js /data collection with working dropdown for aauclub/ var TodoList3 = React.createClass({ render: function() { var _this = this; var createItem = function(item, index) { return ( <li key={ index }> <div>Name: { item.name /**this ".name" changes the attribute displayed in the todo list */ }</div> <div>Position: { item.position }</div> <div>Height: { item.height }</div> <div><span onClick={ _this.props.removeItem.bind(null, item['.key']) } style={{ color: 'red', marginLeft: '10px', cursor: 'pointer' }}> Delete Player </span> </div> </li> ); }; return <ul>{ this.props.items.map(createItem) }</ul>; } }); var TodoApp3 = React.createClass({ mixins: [ReactFireMixin], getInitialState: function() { return { items: [], text: '' }; }, componentWillMount: function() { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com/'); this.bindAsArray(firebaseRef.limitToLast(25), 'items'); }, firstChange: function(e) { this.setState({first: e.target.value}); }, lastChange: function(e) { this.setState({last: e.target.value}); }, phoneChange: function(e) { this.setState({phone: e.target.value}); }, emailChange: function(e) { this.setState({email: e.target.value}); }, addressChange: function(e) { this.setState({address: e.target.value}); }, cityStateZipChange: function(e) { this.setState({cityStateZip: e.target.value}); }, aauCoachChange: function(e) { this.setState({aauCoach: e.target.value}); }, aauEmailChange: function(e) { this.setState({aauEmail: e.target.value}); }, aauPhoneChange: function(e) { this.setState({aauPhone: e.target.value}); }, hsCoachChange: function(e) { this.setState({hsCoach: e.target.value}); }, hsEmailChange: function(e) { this.setState({hsEmail: e.target.value}); }, hsPhoneChange: function(e) { this.setState({hsPhone: e.target.value}); }, gradeChange: function(e) { this.setState({grade: e.target.value}); }, heightChange: function(e) { this.setState({height: e.target.value}); }, weightChange: function(e) { this.setState({weight: e.target.value}); }, vertChange: function(e) { this.setState({vert: e.target.value}); }, positionChange: function(e) { this.setState({position: e.target.value}); }, aauProgramChange: function(e) { this.setState({aauProgram: e.target.value}); }, aauJerseyChange: function(e) { this.setState({aauJersey: e.target.value}); }, schoolChange: function(e) { this.setState({school: e.target.value}); }, hudlChange: function(e) { this.setState({hudl: e.target.value}); }, gpaChange: function(e) { this.setState({gpa: e.target.value}); }, actChange: function(e) { this.setState({act: e.target.value}); }, classRankChange: function(e) { this.setState({classRank: e.target.value}); }, aauClubChange: function(e) { this.setState({aauClub: e.target.value}); }, removeItem: function(key) { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com/'); firebaseRef.child(key).remove(); }, handleSubmit: function(e) { e.preventDefault(); if (this.state.first && this.state.first.trim().length !== 0) { this.firebaseRefs['items'].push({ first: this.state.first,// "name:" changes the input attribute category last: this.state.last, phone: this.state.phone, email: this.state.email, address: this.state.address, cityStateZip: this.state.cityStateZip, aauCoach: this.state.aauCoach, aauEmail: this.state.aauEmail, aauPhone: this.state.aauPhone, hsCoach: this.state.hsCoach, hsEmail: this.state.hsEmail, hsPhone: this.state.hsPhone, grade: this.state.grade, height: this.state.height, weight: this.state.weight, vert: this.state.vert, position: this.state.position, aauProgram: this.state.aauProgram, aauJersey: this.state.aauJersey, school: this.state.school, hudl: this.state.hudl, gpa: this.state.gpa, act: this.state.act, classRank: this.state.classRank, aauClub: this.state.aauClub }); this.setState({ first: '', last: '', phone: '', email: '', address: '', cityStateZip: '', aauCoach: '', aauEmail: '', aauPhone: '', hsCoach: '', hsEmail: '', hsPhone: '', grade: '', height: '', weight: '', vert: '', position: '', aauProgram: '', aauJersey: '', school: '', hudl: '', gpa: '', act: '', classRank: '', aauClub: '' }); } this.state.text = String.Empty; this.state.text2 = String.Empty; this.state.text3 = String.Empty; this.state.first = String.Empty; this.state.last = String.Empty; this.state.phone = String.Empty; this.state.email = String.Empty; this.state.address = String.Empty; this.state.cityStateZip = String.Empty; this.state.aauCoach = String.Empty; this.state.aauEmail = String.Empty; this.state.aauPhone = String.Empty; this.state.hsCoach = String.Empty; this.state.hsEmail = String.Empty; this.state.hsPhone = String.Empty; this.state.grade = String.Empty; this.state.height = String.Empty; this.state.weight = String.Empty; this.state.vert = String.Empty; this.state.position = String.Empty; this.state.aauProgram = String.Empty; this.state.aauJersey = String.Empty; this.state.school = String.Empty; this.state.hudl = String.Empty; this.state.gpa = String.Empty; this.state.act = String.Empty; this.state.classRank = String.Empty; this.state.aauClub = String.Empty; // Using jQuery's animate() method to add smooth page scroll // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area $('html, body').animate({ scrollTop: $(plansFeatures).offset().top - 60 }, 800); }, render: function() { return ( <section className="page"> <form onSubmit={ this.handleSubmit }> <div className="container"> <div className="row"> <div className="col-sm-4"> <div className="timeline-image1 background-gray"> <h2>1</h2> </div> <h5 className="timeline-heading1">Select CLUB</h5> </div> <div className="col-sm-4"> <div className="timeline-image2 background-blue"> <h2>2</h2> </div> <h5 className="timeline-heading2">GENERAL INFORMATION</h5> </div> <div className="col-sm-4"> <div className="timeline-image3 background-gray"> <h2>3</h2> </div> <h5 className="timeline-heading3">BILLING</h5> </div> </div> <div className="row"> <div className="col-md-4 input-box"> <div className="input-container"> <h4>CONTACT INFORMATION</h4> <div className="first-name-container"> <div>FIRST NAME </div> <div><input onChange={ this.firstChange } value={ this.state.first } /></div> </div> <div>LAST NAME <input onChange={ this.lastChange } value={ this.state.last } /></div> <div>PHONE (ATHLETE) <input onChange={ this.phoneChange } value={ this.state.phone } /></div> <div>EMAIL (ATHLETE OR PARENT) <input onChange={ this.emailChange } value={ this.state.email } /></div> <div>ADDRESS <input onChange={ this.addressChange } value={ this.state.address } /></div> <div>CITY/STATE/ZIP <input onChange={ this.cityStateZipChange } value={ this.state.cityStateZip } /></div> <div>AAU COACH NAME <input onChange={ this.aauCoachChange } value={ this.state.aauCoach } /></div> <div>AAU COACH EMAIL <input onChange={ this.aauEmailChange } value={ this.state.aauEmail } /></div> <div>AAU COACH PHONE <input onChange={ this.aauPhoneChange } value={ this.state.aauPhone } /></div> <div>HS COACH NAME <input onChange={ this.hsCoachChange } value={ this.state.hsCoach } /></div> <div>HS COACH EMAIL <input onChange={ this.hsEmailChange } value={ this.state.hsEmail } /></div> <div>HS COACH PHONE <input onChange={ this.hsPhoneChange } value={ this.state.hsPhone } /></div> </div> </div> <div className="col-md-4 input-box"> <div className="input-container"> <h4>ATHLETIC INFORMATION</h4> <div>GRADE/CLASS <input onChange={ this.gradeChange } value={ this.state.grade } /></div> <div>HEIGHT <input onChange={ this.heightChange } value={ this.state.height } /></div> <div>WEIGHT <input onChange={ this.weightChange } value={ this.state.weight } /></div> <div>VERTICAL JUMP <input onChange={ this.vertChange } value={ this.state.vert } /></div> <div>POSITION <input onChange={ this.positionChange } value={ this.state.position } /></div> <div>AAU PROGRAM <input onChange={ this.aauProgramChange } value={ this.state.aauProgram } /></div> <div>AAU JERSEY <input onChange={ this.aauJerseyChange } value={ this.state.aauJersey } /></div> <div>HIGH SCHOOL <input onChange={ this.schoolChange} value={ this.state.school } /></div> <div>HUDL PROFILE <input onChange={ this.hudlChange } value={ this.state.hudl } /></div> </div> </div> <div className="col-md-4 input-box"> <div className="input-container"> <h4>ACADEMIC INFORMATION</h4> <div>GPA <input onChange={ this.gpaChange } value={ this.state.gpa } /></div> <div>ACT <input onChange={ this.actChange } value={ this.state.act } /></div> <div>CLASS RANK <input onChange={ this.classRankChange } value={ this.state.classRank } /></div> </div> <div className="input-container"> <label htmlFor="aau-club">Select Your AAU Club</label> <select onChange={ this.aauClubChange } value={this.state.aauClub} id="aau-club" name="aau-club" className="form-control standalone" type="select" label="Select" placeholder="select"> <option value="Kingdom Hoops">Kingdom Hoops</option> <option value="Rusty's Rascals">Rustys Rascals</option> <option value="McCall MadMen">McCall MadMen</option> <option value="Alex's Angels">Maschoff Monsters</option> </select> </div> </div> </div> </div> <button id="prospect-data-button" className="btn btn-default btn-large center-button">NEXT</button> </form> </section> ); } }); ReactDOM.render(<TodoApp3 />, document.getElementById('generalInformation'));<file_sep>/react-stack/README.md # react-stack Code used for a Pluralsight.com course about a real-time React stack with Flux, Webpack, and Firebase Go check out the course at https://app.pluralsight.com/library/courses/build-isomorphic-app-react-flux-webpack-firebase! #Get up and running * From the command line, clone this repo: `git clone https://github.com/hendrikswan/react-stack && cd react-stack` * Run `npm install` to install all the modules (pegged to specific NPM modules to ensure that it works for you) * Run `node server` to run the webpack dev server <file_sep>/js/coach-gen-info-react.js var CoachGenInfo = React.createClass({ mixins: [ReactFireMixin], getInitialState: function() { return { items: [], text: '' }; }, componentWillMount: function() { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com'); this.bindAsArray(firebaseRef.limitToLast(25), 'prospects'); }, onChange: function(e) { this.setState({text: e.target.value}); }, onChange2: function(e) { this.setState({text2: e.target.value}); }, onChange3: function(e) { this.setState({text3: e.target.value}); }, removeItem: function(key) { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com'); firebaseRef.child(key).remove(); }, handleSubmit: function(e) { e.preventDefault(); if (this.state.text && this.state.text.trim().length !== 0) { this.firebaseRefs['prospects'].push({ name: this.state.text, position: this.state.text2, // "name:" changes the input attribute category height: this.state.text3 }); this.setState({ name: '', position: '', height: '' }); } this.state.text = String.Empty; this.state.text2 = String.Empty; this.state.text3 = String.Empty; }, handleButtonClick: function(event) { // Prevent default anchor click behavior event.preventDefault(); // Using jQuery's animate() method to add smooth page scroll // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area $('html, body').animate({ scrollTop: $(collegeCoachesPlansFeatures).offset().top - 60 }, 800); }, render: function() { return ( <section className="page"> <form onSubmit={ this.handleSubmit }> <div className="container"> <div className="row"> <div className="col-sm-4"> <div className="timeline-image1 background-gray"> <h2>1</h2> </div> <h5 className="timeline-heading1">CREATE ACCOUNT</h5> </div> <div className="col-sm-4"> <div className="timeline-image2 background-blue"> <h2>2</h2> </div> <h5 className="timeline-heading2">GENERAL INFORMATION</h5> </div> <div className="col-sm-4"> <div className="timeline-image3 background-gray"> <h2>3</h2> </div> <h5 className="timeline-heading3">BILLING</h5> </div> </div> <div className="row"> <div className="col-md-offset-2 col-md-4 input-box"> <div className="input-container program-info"> <h4>Coach Information</h4> <div>Name<input onChange={this.handleUserInput} value={ this.state.ccNumber } /></div> <div>Position<input onChange={this.handleUserInput} value={ this.state.ccCode } /></div> <div>Email<input onChange={this.handleUserInput} value={ this.state.ccExpiration } /></div> <div>Phone Number<input onChange={this.handleUserInput} value={ this.state.ccName } /></div> <div>Head Coach Email<input onChange={this.handleUserInput} value={ this.state.ccName } /></div> <div>Head Coach Phone<input onChange={this.handleUserInput} value={ this.state.ccName } /></div> </div> </div> <div className="col-md-4 input-box"> <div id="gender-info" className="input-container"> <h4>Coach Verification</h4> <div>IN ORDER TO VERIFY YOUR EMAIL ADDRESS AS A COLLEGE COACH, PLEASE MAKE SURE THE EMAIL ADDRESS SEEN BELOW IS CORRECT SO WE CAN SEND AN EMAIL TO VERIFY IT IS A UNIVERSITY EMAIL.</div> <h4>Email just entered</h4> </div> </div> </div> </div> <button onClick={this.handleButtonClick} className="btn btn-default btn-large center-button">Next</button> </form> </section> ); } }); ReactDOM.render(<CoachGenInfo />, document.getElementById('coachGenInfo'));<file_sep>/_site/js/todoAppFirebaseImplicit.js /** @jsx React.DOM */ var TodoList3 = React.createClass({ render: function() { var _this = this; var createItem = function(item, index) { return ( <li key={ index }> <div>Name: { item.name /**this ".name" changes the attribute displayed in the todo list */ }</div> <div>Position: { item.position }</div> <div>Height: { item.height }</div> <div><span onClick={ _this.props.removeItem.bind(null, item['.key']) } style={{ color: 'red', marginLeft: '10px', cursor: 'pointer' }}> Delete Player </span> </div> </li> ); }; return <ul>{ this.props.items.map(createItem) }</ul>; } }); var TodoApp3 = React.createClass({ mixins: [ReactFireMixin], getInitialState: function() { return { items: [], text: '' }; }, componentWillMount: function() { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com/players/'); this.bindAsArray(firebaseRef.limitToLast(25), 'items'); }, onChange: function(e) { this.setState({text: e.target.value}); }, onChange2: function(e) { this.setState({text2: e.target.value}); }, onChange3: function(e) { this.setState({text3: e.target.value}); }, removeItem: function(key) { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com/players/'); firebaseRef.child(key).remove(); }, handleSubmit: function(e) { e.preventDefault(); if (this.state.text && this.state.text.trim().length !== 0) { this.firebaseRefs['items'].push({ name: this.state.text, position: this.state.text2, // "name:" changes the input attribute category height: this.state.text3 }); this.setState({ name: '', position: '', height: '' }); } this.state.text = String.Empty; this.state.text2 = String.Empty; this.state.text3 = String.Empty; }, render: function() { return ( <div> <TodoList3 items={ this.state.items } removeItem={ this.removeItem } /> <form onSubmit={ this.handleSubmit }> <div>Name: <input onChange={ this.onChange } value={ this.state.text } /></div> <div>Position: <input onChange={ this.onChange2 } value={ this.state.text2 } /></div> <div>Height: <input onChange={ this.onChange3 } value={ this.state.text3 } /></div> <button>{ 'Add #' + (this.state.items.length + 1) }</button> </form> </div> ); } }); React.render(<TodoApp3 />, document.getElementById('todoApp3'));<file_sep>/js/rusty-react.js var ProfileViewPage = React.createClass ({ mixins: [ReactFireMixin], componentWillMount: function() { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com/prospects'); rootRef.child('-KAl8nq_0e7l0jgvnE-u'); }, handleContactClick: function(event) { document.getElementById('profile-contact-info').style.display='block'; document.getElementById('profile-athletic-info').style.display='none'; document.getElementById('profile-academic-info').style.display='none'; document.getElementById('player-recruiting-interest').style.display='none'; }, handleAthleticClick: function(event) { document.getElementById('profile-contact-info').style.display='none'; document.getElementById('profile-athletic-info').style.display='block'; document.getElementById('profile-academic-info').style.display='none'; document.getElementById('player-recruiting-interest').style.display='none'; }, handleAcademicClick: function(event) { document.getElementById('profile-contact-info').style.display='none'; document.getElementById('profile-athletic-info').style.display='none'; document.getElementById('profile-academic-info').style.display='block'; document.getElementById('player-recruiting-interest').style.display='none'; }, handleRecruitingClick: function(event) { document.getElementById('profile-contact-info').style.display='none'; document.getElementById('profile-athletic-info').style.display='none'; document.getElementById('profile-academic-info').style.display='none'; document.getElementById('player-recruiting-interest').style.display='block'; }, render: function() { return ( <section id="profile" className="page"> <div className="container"> <div id="profile-top-row" className="row profile-top-row"> <div className="col-sm-3"> <div id="profile-picture" className="background-blue"> <PlayerPic prospects={ this.state.prospects } /> </div> </div> <div className="col-sm-6"> <div id="" className=""> <PlayerProfileBasics prospects={ this.state.prospects } /> </div> </div> <div className="col-sm-3"> <div id="notifications" className="background-blue"> <h5>add to notifications</h5> </div> </div> </div> <div className="row"> <div className="col-sm-3"> <div id="club-logo" className="background-blue"> <h5>CLUB LOGO</h5> </div> <div id="" className="data-cat-btn background-gray" onClick={this.handleContactClick}> <h5>Contact Information</h5> </div> <div id="" className="data-cat-btn background-gray" onClick={this.handleAthleticClick}> <h5>Athletic Information</h5> </div> <div id="" className="data-cat-btn background-gray" onClick={this.handleAcademicClick}> <h5>Academic Information</h5> </div> <div id="" className="data-cat-btn background-blue" onClick={this.handleRecruitingClick}> <h5>Recruiting Interest</h5> </div> </div> <div id="athlete-info-container" className="col-sm-9"> <div> <PlayerProfileContactInfo prospects={ this.state.prospects }/> <PlayerProfileAthleticInfo prospects={ this.state.prospects }/> <PlayerProfileAcademicInfo prospects={ this.state.prospects }/> <PlayerRecruitingInterest prospects={ this.state.prospects }/> </div> </div> </div> </div> </section> ); } }); ReactDOM.render(<ProfileViewPage />, document.getElementById('rusty-test') );<file_sep>/js/mens-womens-registration-react.js var CoachRegistration = React.createClass({ mixins: [ReactFireMixin], getInitialState: function() { return { items: [], text: '' }; }, componentWillMount: function() { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com/players/'); this.bindAsArray(firebaseRef.limitToLast(25), 'items'); }, onChange: function(e) { this.setState({text: e.target.value}); }, onChange2: function(e) { this.setState({text2: e.target.value}); }, onChange3: function(e) { this.setState({text3: e.target.value}); }, removeItem: function(key) { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com/players/'); firebaseRef.child(key).remove(); }, handleSubmit: function(e) { e.preventDefault(); if (this.state.text && this.state.text.trim().length !== 0) { this.firebaseRefs['items'].push({ name: this.state.text, position: this.state.text2, // "name:" changes the input attribute category height: this.state.text3 }); this.setState({ name: '', position: '', height: '' }); } this.state.text = String.Empty; this.state.text2 = String.Empty; this.state.text3 = String.Empty; }, handleButtonClick: function(event) { // Prevent default anchor click behavior event.preventDefault(); // Store hash // Using jQuery's animate() method to add smooth page scroll // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area $('html, body').animate({ scrollTop: $(collegeCoachRegistration).offset().top - 60 }, 800); }, render: function() { return ( <section className="page2"> <form className="text-center" onSubmit={ this.handleSubmit }> <div id="registration-sized" className="container"> <div className="row"> <div className="col-sm-12"> <div className="header text-center"> <h1>College Coach Registration</h1> </div> </div> </div> <div className="row"> <div className="col-sm-12 coach-registration background-light-gray"> <div id="" className="col-sm-8 background-light-gray men-women-coach text-left"> <h5>MENS COLLEGE COACH (NCAA, NAIA, NJCAA)</h5> </div> <div onClick={this.handleButtonClick} id="" className="col-sm-4 background-blue register-btn"> <h5>Click Here To Register</h5> <p>(Basic Account: Free)</p> </div> </div> </div> <div className="row"> <div className="col-sm-12 coach-registration background-light-gray"> <div id="" className="col-sm-8 background-light-gray men-women-coach text-left"> <h5>WOMENS COLLEGE COACH (NCAA, NAIA, NJCAA)</h5> </div> <div onClick={this.handleButtonClick} id="" className="col-sm-4 background-blue register-btn"> <h5>Click Here To Register</h5> <p>(Basic Account: Free)</p> </div> </div> </div> </div> </form> </section> ); } }); ReactDOM.render(<CoachRegistration />, document.getElementById('mensWomensRegistration'));<file_sep>/README.md # prospectsource Prospect Source Website Local Server http Hosting I. To edit through Koding.com 1. sign in with github 2. refresh page 3. go to three dots next to “koding-vm-0” in the top left hand corner and copy assigned URL into browser 4. put “:8080” at the end and it will take me to the editable website. ![alt text] (img/step1.png) II. To edit through text-wrangler 1. command space to pull up iterm 2. drag page into iterm and backspace to the github repo, then "function arrow" to get to the front of the command and type "cd" at the front of it. 2. type in “http-server” Helpful commands for terminal: ``` $control c ``` 1.ends serve ``` $cd ~ ``` 2. takes you to home directory ----- Notes: Tmux https://robots.thoughtbot.com/a-tmux-crash-course <file_sep>/react-stack/src/routes/index.js import React from 'react'; import App from '../components/App.jsx'; import Chat from '../components/Chat.jsx'; import SelectClub from '../components/SelectClub.jsx'; import ProspectRegistration from '../components/ProspectRegistration.jsx'; import GeneralInformation from '../components/GeneralInformation.jsx'; import Login from '../components/Login.jsx'; import Router from 'react-router'; let Route = Router.Route; let DefaultRoute = Router.DefaultRoute; let routes = ( <Route path="/" handler={App}> <DefaultRoute handler={Login} /> <Route path="prospectregistration" handler={ProspectRegistration} /> <Route path="select_club" handler={SelectClub} /> <Route path="General_Information" handler={GeneralInformation} /> // <Route path="Plans and Features " handler={GeneralInformation} /> // <Route path="Billing" handler={GeneralInformation} /> -- payment processinng of choice // <Route path="Thank You" handler={GeneralInformation} /> // <Route path="Dashboard" handler={GeneralInformation} /> <Route path="chat" handler={Chat} /> <Route path="chat/:channel" handler={Chat} /> <Route path="login" handler={Login} /> </Route> ); Router.run(routes, Router.HashLocation, (Root)=> { React.render(<Root />, document.getElementById('container')); }); <file_sep>/js/billing-react.js var Billing = React.createClass({ mixins: [ReactFireMixin], getInitialState: function() { return { items: [], text: '' }; }, componentWillMount: function() { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com'); this.bindAsArray(firebaseRef.limitToLast(25), 'prospects'); }, onChange: function(e) { this.setState({text: e.target.value}); }, onChange2: function(e) { this.setState({text2: e.target.value}); }, onChange3: function(e) { this.setState({text3: e.target.value}); }, removeItem: function(key) { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com'); firebaseRef.child(key).remove(); }, handleButtonClick: function(event) { // Prevent default anchor click behavior event.preventDefault(); // Using jQuery's animate() method to add smooth page scroll // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area $('html, body').animate({ scrollTop: $(completedRegistration).offset().top - 100 }, 800); }, render: function() { return ( <section className="page"> <form onSubmit={ this.handleSubmit }> <div className="container"> <div className="row"> <div className="col-sm-4"> <div className="timeline-image1 background-gray"> <h2>1</h2> </div> <h5 className="timeline-heading1">SELECT CLUB</h5> </div> <div className="col-sm-4"> <div className="timeline-image2 background-gray"> <h2>2</h2> </div> <h5 className="timeline-heading2">GENERAL INFORMATION</h5> </div> <div className="col-sm-4"> <div className="timeline-image3 background-blue"> <h2>3</h2> </div> <h5 className="timeline-heading3">BILLING</h5> </div> </div> <div className="row"> <div className="col-md-4 input-box"> <div id="fee-info" className=""> <h4><u>Once registered...</u></h4> <div>you will have access to our premium services: <ul> <li>- Video Service</li> <li>- Marketing Service</li> <li>- Consulting Service</li> </ul> When premium services are purchased, we will bill the credit card on file. You can delete or remove your credit card and profile at any time. </div> </div> </div> <div className="col-md-4 input-box"> <div className="input-container cc-info"> <h3>CC Information</h3> <div>CC Number<input onChange={this.handleUserInput} value={ this.state.ccNumber } /></div> <div>Security Code<input onChange={this.handleUserInput} value={ this.state.ccCode } /></div> <div>Expiration <input onChange={this.handleUserInput} value={ this.state.ccExpiration } /></div> <div>Name On Card<input onChange={this.handleUserInput} value={ this.state.ccName } /></div> </div> </div> <div className="col-md-4 input-box"> <div className="input-container cc-info"> <h3>Billing Address</h3> <div>Street<input onChange={this.handleUserInput} value={ this.state.billingStreet } /></div> <div>City<input onChange={this.handleUserInput} value={ this.state.billingCity } /></div> <div>State <input onChange={this.handleUserInput} value={ this.state.billingState } /></div> <div>Zip<input onChange={this.handleUserInput} value={ this.state.billingZip } /></div> </div> </div> </div> </div> <a onClick={this.handleButtonClick} className="btn btn-default btn-large center-button">Finish</a> </form> </section> ); } }); ReactDOM.render(<Billing />, document.getElementById('billing'));<file_sep>/js/todoAppFirebaseImplicit.js var TodoList3 = React.createClass({ render: function() { var _this = this; var createItem = function(item, index) { return ( <li key={ index }> <div>key: { item['.key'] }</div> <div>first name: { item.first}</div> <div>position: { item.position }</div> <div>height: { item.height }</div> <div><span onClick={ _this.props.removeItem.bind(null, item['.key']) } style={{ color: 'red', marginLeft: '10px', cursor: 'pointer' }}> Delete Player </span> </div> </li> ); }; return <ul>{ this.props.prospects.map(createItem) }</ul>; } }); var TodoApp3 = React.createClass({ mixins: [ReactFireMixin], getInitialState: function() { return { items: [], name: '', position: '', height: '', }; }, componentWillMount: function() { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com'); this.bindAsArray(firebaseRef.limitToLast(25), 'prospects'); }, nameChange: function(e) { this.setState({name: e.target.value}); }, onChange2: function(e) { this.setState({position: e.target.value}); }, onChange3: function(e) { this.setState({height: e.target.value}); }, removeItem: function(key) { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com'); firebaseRef.child(key).remove(); }, handleSubmit: function(e) { e.preventDefault(); if (this.state.name && this.state.name.trim().length !== 0) { this.firebaseRefs['prospects'].push({ name: this.state.name, position: this.state.position, // "name:" changes the input attribute category height: this.state.height }); this.setState({ name: '', position: '', height: '' }); } this.state.name = String.Empty; this.state.position = String.Empty; this.state.height = String.Empty; }, render: function() { return ( <div> <TodoList3 prospects={ this.state.prospects } removeItem={ this.removeItem } /> <form onSubmit={ this.handleSubmit }> <div>Name: <input onChange={ this.nameChange } value={ this.state.name } /></div> <div>Position: <input onChange={ this.onChange2 } value={ this.state.position } /></div> <div>Height: <input onChange={ this.onChange3 } value={ this.state.height } /></div> <button>{ 'Add #' + (this.state.items.length + 1) }</button> </form> </div> ); } }); ReactDOM.render(<TodoApp3 />, document.getElementById('todoApp3'));<file_sep>/js/college-coach-confirm-react.js var CoachRegistrationConfirmation = React.createClass({ mixins: [ReactFireMixin], getInitialState: function() { return { items: [], text: '' }; }, componentWillMount: function() { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com'); this.bindAsArray(firebaseRef.limitToLast(25), 'prospects'); }, onChange: function(e) { this.setState({text: e.target.value}); }, onChange2: function(e) { this.setState({text2: e.target.value}); }, onChange3: function(e) { this.setState({text3: e.target.value}); }, removeItem: function(key) { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com'); firebaseRef.child(key).remove(); }, handleSubmit: function(e) { e.preventDefault(); if (this.state.text && this.state.text.trim().length !== 0) { this.firebaseRefs['prospects'].push({ name: this.state.text, position: this.state.text2, // "name:" changes the input attribute category height: this.state.text3 }); this.setState({ name: '', position: '', height: '' }); } this.state.text = String.Empty; this.state.text2 = String.Empty; this.state.text3 = String.Empty; }, handleButtonClick: function(event) { // Prevent default anchor click behavior event.preventDefault(); // Store hash // Using jQuery's animate() method to add smooth page scroll // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area $('html, body').animate({ scrollTop: $(coachesConfirm).offset().top - 100 }, 800); }, render: function() { return ( <section className="page"> <form onSubmit={ this.handleSubmit }> <div className="container"> <div className="row"> <div className="col-sm-12"> <h3 className="text-center" >You have successfully created your college coach account!</h3> <p>Please visit your dashboard and use our service to search and follow prospects in our database. This platform is intended to help your coaching staff discover new prospects and gain more information on prospects you already follow. </p> <p>Thanks for choosing Prospect Source!</p> </div> </div> </div> <button onClick={this.handleButtonClick} className="btn btn-default btn-large center-button">View Profile</button> </form> </section> ); } }); ReactDOM.render(<CoachRegistrationConfirmation />, document.getElementById('coachConfirm')); <file_sep>/js/todoAppOriginal.js /** @jsx React.DOM */ var TodoList1 = React.createClass({ render: function() { var createItem = function(item, index) { return <li key={ index }>{item.text}</li>; }; return <ul>{ this.props.items.map(createItem) }</ul>; } }); var TodoApp1 = React.createClass({ getInitialState: function() { return {items: [], name: ""}; }, onChange: function(e) { this.setState({text: e.target.value}); }, handleSubmit: function(e) { e.preventDefault(); if (this.state.text) { var nextItems = this.state.items.concat([{ text: this.state.text }]); this.setState({ items: nextItems, text: "" }); } }, render: function() { return ( <div> <TodoList1 items={ this.state.items } /> <form onSubmit={ this.handleSubmit }> <input onChange={ this.onChange } value={ this.state.text } /> <button>{ "Add #" + (this.state.items.length + 1) }</button> </form> </div> ); } }); React.render(<TodoApp1 />, document.getElementById("todoApp1"));<file_sep>/js/program-info-react.js var ProgramInfo = React.createClass({ mixins: [ReactFireMixin], getInitialState: function() { return { items: [], text: '' }; }, componentWillMount: function() { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com'); this.bindAsArray(firebaseRef.limitToLast(25), 'prospects'); }, onChange: function(e) { this.setState({text: e.target.value}); }, onChange2: function(e) { this.setState({text2: e.target.value}); }, onChange3: function(e) { this.setState({text3: e.target.value}); }, removeItem: function(key) { var firebaseRef = new Firebase('https://sweltering-fire-7944.firebaseio.com'); firebaseRef.child(key).remove(); }, handleSubmit: function(e) { e.preventDefault(); if (this.state.text && this.state.text.trim().length !== 0) { this.firebaseRefs['prospects'].push({ name: this.state.text, position: this.state.text2, // "name:" changes the input attribute category height: this.state.text3 }); this.setState({ name: '', position: '', height: '' }); } this.state.text = String.Empty; this.state.text2 = String.Empty; this.state.text3 = String.Empty; }, render: function() { return ( <section className="page"> <form onSubmit={ this.handleSubmit }> <div className="container"> <div className="row"> <div className="col-sm-4"> <div className="timeline-image1 background-gray"> <h2>1</h2> </div> <h5 className="timeline-heading1">CREATE ACCOUNT</h5> </div> <div className="col-sm-4"> <div className="timeline-image2 background-blue"> <h2>2</h2> </div> <h5 className="timeline-heading2">GENERAL INFORMATION</h5> </div> <div className="col-sm-4"> <div className="timeline-image3 background-gray"> <h2>3</h2> </div> <h5 className="timeline-heading3">INVITE PROSPECTS</h5> </div> </div> <div className="row"> <div className="col-md-offset-2 col-md-4 input-box"> <div className="input-container program-info"> <h4>Program Information</h4> <div>Program Name<input onChange={this.handleUserInput} value={ this.state.ccNumber } /></div> <div>Phone (Program Contact)<input onChange={this.handleUserInput} value={ this.state.ccCode } /></div> <div>Email (Program Contact) <input onChange={this.handleUserInput} value={ this.state.ccExpiration } /></div> <div>Address<input onChange={this.handleUserInput} value={ this.state.ccName } /></div> <div>City/State/Zip <input onChange={this.handleUserInput} value={ this.state.ccName } /></div> <div>Coach/Director Name <input onChange={this.handleUserInput} value={ this.state.ccName } /></div> <div>Program Website <input onChange={this.handleUserInput} value={ this.state.ccName } /></div> <div>Upload Logo<input className="custom-file-input" type="file" name="pic" accept="image/*" /></div> </div> </div> <div className="col-md-4 input-box"> <div id="gender-info" className="input-container"> <h4>Prospect Information</h4> <div><input type="checkbox" onChange={this.handleUserInput} value={ this.state.billingStreet } /><span>Mens</span></div> <div><input type="checkbox" onChange={this.handleUserInput} value={ this.state.billingCity } /><span>Womens</span></div> </div> </div> </div> </div> <button className="btn btn-default btn-large center-button">Finish</button> </form> </section> ); } }); ReactDOM.render(<ProgramInfo />, document.getElementById('program-info'));
1595b96e59f29c81801ef8cefc74090c2ca59b9e
[ "JavaScript", "Markdown" ]
26
JavaScript
prospectsource/prospectsource.github.io
21eb9012759a45c79f1b5eabc90dc9ddfe1220c8
70ddafda51a77bd87c38f346fb3fe105c175b2b3
refs/heads/master
<repo_name>bwong199/MEAN-discussion-board<file_sep>/server/config/routes.js var users = require("./../controllers/users.js"); var topics = require("./../controllers/topics.js"); var posts = require("./../controllers/posts.js"); var comments = require("./../controllers/comments.js"); module.exports = function(app) { app.post("/main", function(req, res) { req.session.name = req.body.name; res.render("/dashboard", {name: req.session.name} ); }); app.get("/", function(req, res) { res.render("index"); }); app.get("/showTopic", function(req, res) { res.render("main", {name: req.session.name} ); }); app.get("/topic", function(req, res) { topics.show(req, res); }); app.get("/comment", function(req, res) { comments.show(req, res); }); app.get("/oneTopic/:id", function(req, res) { topics.showOne(req, res); }); app.get("/post/:id", function(req, res) { posts.show(req, res); }); app.post("/savePost/:id", function(req, res) { posts.savePost(req, res); }); app.post("/saveComment/:id", function(req, res) { posts.saveComment(req, res); }); app.post("/saveUp/:id", function(req, res) { posts.saveUp(req, res); }); app.post("/saveDown/:id", function(req, res) { posts.saveDown(req, res); }); app.get("/comment/:id", function(req, res) { posts.showComment(req, res); }); app.get("/like/:id", function(req, res) { posts.showLike(req, res); }); app.get("/user", function(req, res) { users.showOne(req, res); }); app.get("/searchUser/:id", function(req, res) { users.showUser(req, res); }); app.post("/saveUser", function(req, res) { users.saveUser(req, res); }); app.post("/saveTopic", function(req, res) { topics.saveTopic(req, res); }); app.get("/topic/:id", function(req, res) { topics.showOne(req, res); }); app.get("/deleteTopic/:id", function(req, res) { topics.deleteTopic(req, res); }); };<file_sep>/public/javascripts/controllers/profilesController.js discussions_app.controller("ProfilesController", function($scope, $routeParams, UserFactory) { UserFactory.getUser(function (data) { $scope.users2 = data; }); });<file_sep>/server/models/comment.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var CommentSchema = new mongoose.Schema({ name: String, comment: String, _postId: {type: Schema.ObjectId, ref: 'Post'}, _userId: {type: Schema.ObjectId, ref: 'User'}, }); mongoose.model('Comment', CommentSchema); <file_sep>/public/javascripts/controllers/postsController.js discussions_app.controller("PostsController", function($scope, topicFactory, postFactory, $routeParams, UserFactory) { postFactory.getPost(function (data) { console.log(data); $scope.posts = data; }); postFactory.getComment(function (data) { $scope.comments = data; }); topicFactory.getTopic(function (data) { $scope.topics = data; }); topicFactory.getOneTopic(function (data) { $scope.oneTopic = data; }); UserFactory.getUser(function (data) { $scope.users = data; }); UserFactory.getCurrentUser(function(info){ $scope.current_user = info; }); UserFactory.getUser(function (data) { $scope.users2 = data; }); $scope.addPost = function() { $scope.new_post.name = $scope.users2.name; $scope.new_post._userId = $scope.users2._id; $scope.new_post._topicId = $scope.oneTopic._id; postFactory.addPost($scope.new_post, function () { postFactory.getPost(function (data) { $scope.posts = data; }); $scope.new_post = {}; }); }; $scope.addComment = function(id, comment, userName, userId) { var commentValue = comment.comment; var newComment = {comment: commentValue, name: userName, userId: userId}; postFactory.addComment(id, newComment, function () { postFactory.getComment(function (data) { $scope.comments = data; }); $scope.new_comment = {}; }); }; $scope.addUp = function(id, up) { postFactory.addUp(id, up, function () { postFactory.getLike(function (data) { $scope.ups = data; }); $scope.new_up = {}; }); }; $scope.addDown = function(id, like) { postFactory.addDown(id, like, function () { postFactory.getUp(function (data) { $scope.downs = data; }); $scope.new_down = {}; }); }; });<file_sep>/server/models/post.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var PostSchema = new mongoose.Schema({ name:String, post:String, _userId: {type: Schema.ObjectId, ref: 'User'}, _topicId: {type: Schema.ObjectId, ref: 'Topic'}, comment: [{name: String, comment: String, userId: String}], up: [{count: Number}], down: [{count: Number}], }); mongoose.model('Post', PostSchema); <file_sep>/README.md # full-mean Full MEAN Stack Project Reddit Clone where people can post a topic and others can make replies to the topic. Comments can be made to each reply. The app was built using Angular, NodeJS, MongoDB, and Express. To dos: Mount authentication on top. <file_sep>/public/javascripts/controllers/dashboardsController.js discussions_app.controller("DashboardController", function($scope, topicFactory, UserFactory) { UserFactory.getCurrentUser(function(info){ $scope.current_user = info; }); topicFactory.getTopic(function (data) { $scope.topics = data; }); UserFactory.getUser(function (data) { $scope.users2 = data; }); $scope.addTopic = function() { $scope.new_topic.name = $scope.users2.name $scope.new_topic._userId = $scope.users2._id topicFactory.addTopic($scope.new_topic, function () { topicFactory.getTopic(function (data) { $scope.topics = data; }); $scope.new_topic = {}; }); }; });<file_sep>/server/models/topic.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var TopicSchema = new mongoose.Schema({ topic: String, name:String, description: String, category: String, _userId: {type: Schema.ObjectId, ref: 'User'}, post: [{type: Schema.Types.ObjectId, ref: 'Post'}], }); mongoose.model('Topic', TopicSchema); <file_sep>/public/javascripts/factories/postFactory.js discussions_app.factory("postFactory", function( $http, $routeParams) { var factory = {}; factory.getPost = function(callback) { $http.get("/post/" + $routeParams.id).success(function(output) { posts = output; callback(posts); }); }; factory.getComment = function(callback) { $http.get("/comment/" + $routeParams.id).success(function(output) { callback(output); }); }; factory.getLike = function(callback) { $http.get("/like/" + $routeParams.id).success(function(output) { callback(output); }); }; factory.addPost = function(info, callback) { $http.post("/savePost/" + $routeParams.id, info).success(function() { }); }; factory.addComment = function(id, info, callback) { console.log(info); $http.post("/saveComment/" + id , info).success(function() { }); }; factory.addUp = function(id, info, callback) { $http.post("/saveUp/" + id, info).success(function() { }); }; factory.addDown = function(id, info, callback) { $http.post("/saveDown/" + id, info).success(function() { }); }; return factory; });<file_sep>/public/javascripts/controllers/usersController.js discussions_app.controller("UsersController", function($scope, $location, UserFactory) { UserFactory.getUser(function (data) { $scope.users2 = data; }); UserFactory.searchUser(function (data) { $scope.userResult = data; }); $scope.addUser = function() { UserFactory.addNewUser($scope.new_user2, function () { UserFactory.getUser(function (data) { $scope.users2 = data; }); $scope.new_user2 = {}; }); }; }); <file_sep>/public/javascripts/factories/userFactory.js discussions_app.factory("UserFactory", function($http, $routeParams) { var currentUser = {}; var factory = {}; factory.getUser = function(callback) { $http.get("/user").success(function(output) { users2 = output; callback(users2); }); }; factory.searchUser = function(callback) { $http.get("/searchUser/" + $routeParams.id).success(function(output) { userResult = output; callback(userResult); }); }; factory.getCurrentUser = function(callback){ callback(currentUser); } factory.addNewUser = function(info, callback) { $http.post("/saveUser", info).success(function() { users2.push({name: info.name}); callback(users2); }); }; return factory; }); <file_sep>/server/controllers/posts.js var mongoose = require('mongoose'); var Post = mongoose.model('Post'); var Topic = mongoose.model('Topic'); var Comment = mongoose.model('Comment'); var User = mongoose.model('User'); var ObjectId = require('mongoose').Types.ObjectId; module.exports = (function() { return { show: function(req, res) { Topic.findOne({_id: req.params.id}) .populate('post') .populate('comment') .exec(function(err, result) { res.json(result) }); }, showComment: function(req, res) { Topic.findOne({_id: req.params.id}) .populate('post') .exec(function(err, result) { res.json(result) }); }, showLike: function(req, res) { Topic.findOne({_id: req.params.id}) .populate('post') .exec(function(err, result) { res.json(result) }); }, savePost: function(req, res) { Topic.findOne({_id: req.body._topicId}, function(err, topic){ var post = new Post(req.body); post._topicId = topic._id; topic.post.push(post); post.save(function(err){ topic.save(function(err){ if(err) { console.log('Error'); } else { console.log('Successfully added posts to topic', post); res.redirect('/'); } }) }) }); User.findOne({_id: req.body._userId}, function(err, user){ var post = new Post(req.body); post._userId = user._id; user.post.push(post); post.save(function(err){ user.save(function(err){ if(err) { console.log('Error'); } else { console.log('Successfully added posts to user', post); res.redirect('/'); } }) }) }); }, saveComment: function(req, res) { Post.findById(req.params.id, function(err, post){ console.log(post); console.log(req.body); var comment = req.body; post.comment.push(comment); post.save(function(err){ if(err) { console.log('Error'); } else { console.log('Successfully added comment to post', comment); res.redirect('/'); } }) }); User.findOne({_id: req.body.userId}, function(err, user){ var comment = new Comment(req.body); comment._userId = user._id; user.comment.push(comment); comment.save(function(err){ user.save(function(err){ if(err) { console.log('Error'); } else { console.log('Successfully added comments to user', comment); res.redirect('/'); } }) }) }); }, saveUp: function(req, res) { Post.findById(req.params.id, function(err, post){ var up = req.body; post.up.push(up); post.save(function(err){ if(err) { console.log('Error'); } else { console.log('Successfully added upvote', up); res.redirect('/'); } }) }); }, saveDown: function(req, res) { Post.findById(req.params.id, function(err, post){ var down = req.body; post.down.push(down); post.save(function(err){ if(err) { console.log('Error'); } else { console.log('Successfully added downvote', down); res.redirect('/'); } }) }); }, } })();<file_sep>/server/controllers/users.js var mongoose = require('mongoose'); var User = mongoose.model('User'); module.exports = (function() { return { showOne: function(req, res) { User.findOne({}, function(err, results) { if(err) { console.log("Mongo Database Show User Errors:", err); } else { res.json(results); // console.log(results) } }).sort({_id: -1}).limit(1); }, showUser: function(req, res) { User.findOne({_id: req.params.id}) .populate('topic') .populate('post') .populate('comment') .exec(function(err, result) { res.json(result) }); }, saveUser: function(req, res) { // console.log('hello'); var user = new User(req.body); // console.log(req.body) user.save(function(err) { if(err) { console.log("Adding user error:", err); res.redirect("/"); } else { console.log("User POSTED", user); } }); }, deleteUser: function(req, res) { User.remove({_id: req.params.id}, function(err) { if(err) { console.log("User delete error:", err); } else { console.log("User deleted!"); res.redirect("/"); } }); } } })();<file_sep>/public/javascripts/app.js var discussions_app = angular.module('discussions_app', ['ngRoute']); discussions_app.config(function ($routeProvider, $locationProvider) { $routeProvider .when('/',{ templateUrl: 'static/partials/main.ejs', controller: 'UsersController' }) .when('/dashboard',{ templateUrl: 'static/partials/topic.ejs', controller: 'DashboardController' }) .when('/topic/:id',{ templateUrl: 'static/partials/post.ejs', controller: 'PostsController' }) .when('/profile/:id',{ templateUrl: 'static/partials/profile.ejs', controller: 'UsersController' }) .otherwise({ redirectTo: '/' }); });<file_sep>/public/javascripts/controllers/commentsController.js // Now lets create a controller with some hardcoded data! discussions_app.controller("postsController", function($scope, topicFactory, postFactory, $routeParams) { postFactory.getPost(function (data) { $scope.posts = data; console.log($scope.posts) }); topicFactory.getTopic(function (data) { $scope.topics = data; }); topicFactory.getOneTopic(function (data) { $scope.oneTopic = data; // console.log($scope.oneTopic) }); $scope.addPost = function() { postFactory.addPost($scope.new_post, function () { postFactory.getPost(function (data) { $scope.posts = data; }); $scope.new_post = {}; }); }; $scope.addComment = function() { postFactory.addComment($scope.new_comment, function () { postFactory.getComment(function (data) { $scope.comments = data; }); $scope.new_comment = {}; }); }; });
35cc1576f02f7aa83b62e9bd05e161dd170b9c44
[ "JavaScript", "Markdown" ]
15
JavaScript
bwong199/MEAN-discussion-board
b74dbd3e78ac54fe5c0a8547902dde09b3db8c94
9bdcaef0bd8e9e4dd4c15614554db431de5280a1
refs/heads/master
<repo_name>kingalois/calendarexport<file_sep>/at.am.googlecalendarexporter.product/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <artifactId>at.am.googlecalendarexporter.product</artifactId> <packaging>eclipse-repository</packaging> <parent> <groupId>at.am</groupId> <artifactId>at.am.common.target</artifactId> <version>1.0.0-SNAPSHOT</version> </parent> <build> <plugins> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.1</version> <executions> <execution> <id>copy-resourcesX86</id> <!-- here the phase you need --> <phase>compile</phase> <goals> <goal>copy-resources</goal> </goals> <configuration> <outputDirectory>${basedir}/target/products/GoogleKalendarExport/win32/win32/x86</outputDirectory> <resources> <resource> <directory>resources</directory> <filtering>true</filtering> </resource> </resources> </configuration> </execution> <execution> <id>copy-resourcesX64</id> <!-- here the phase you need --> <phase>compile</phase> <goals> <goal>copy-resources</goal> </goals> <configuration> <outputDirectory>${basedir}/target/products/GoogleKalendarExport/win32/win32/x86_64</outputDirectory> <resources> <resource> <directory>resources</directory> <filtering>true</filtering> </resource> </resources> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.eclipse.tycho</groupId> <artifactId>tycho-p2-repository-plugin</artifactId> <version>${tycho.version}</version> <configuration> <includeAllDependencies>true</includeAllDependencies> </configuration> </plugin> <plugin> <groupId>org.eclipse.tycho</groupId> <artifactId>tycho-p2-director-plugin</artifactId> <version>${tycho.version}</version> <executions> <execution> <id>materialize-products</id> <goals> <goal>materialize-products</goal> </goals> </execution> <execution> <id>archive-products</id> <goals> <goal>archive-products</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <groupId>at.am.googlecalendarexporter</groupId> </project><file_sep>/at.am.googlecalendarexporter.apiwrapper/src/at/am/googlecalendar/connection/GoogleCalendarConnector.java package at.am.googlecalendar.connection; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.List; import java.util.logging.Logger; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.store.FileDataStoreFactory; import com.google.api.services.calendar.CalendarScopes; import at.am.common.logging.LogFactory; /** * Class handle the authorization to the google api to access the calendar * * @author <NAME> * */ public class GoogleCalendarConnector { private static final Logger log = LogFactory.makeLogger(); /** Application name. */ private static final String APPLICATION_NAME = "Google Calendar Export"; /** Directory to store user credentials for this application. */ private static final java.io.File DATA_STORE_DIR = new java.io.File("./"); /** Global instance of the {@link FileDataStoreFactory}. */ private static FileDataStoreFactory DATA_STORE_FACTORY; /** Global instance of the JSON factory. */ private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); /** Global instance of the HTTP transport. */ private static HttpTransport HTTP_TRANSPORT; /** Global instance of the scopes required by this quickstart. */ private static final List<String> SCOPES = Arrays.asList(CalendarScopes.CALENDAR_READONLY); static { try { HTTP_TRANSPORT = new NetHttpTransport();// GoogleNetHttpTransport.newTrustedTransport(); DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR); } catch (Throwable t) { t.printStackTrace(); System.exit(1); } } /** * Creates an authorized Credential object. * * @return an authorized Credential object. * @throws IOException */ public static Credential authorize() throws IOException { // Load client secrets. File f = new File("client_secret.json"); log.info("path of secrets: " + f.getAbsolutePath()); if(!f.exists()){ throw new IOException("client_secret.json file does not exist: " + f.getAbsolutePath()); } InputStream in = new FileInputStream("client_secret.json"); GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in)); // Build flow and trigger user authorization request. GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES).setDataStoreFactory(DATA_STORE_FACTORY) .setAccessType("offline").build(); Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); log.info("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath()); return credential; } /** * Build and return an authorized Calendar client service. * * @return an authorized Calendar client service * @throws IOException */ public static com.google.api.services.calendar.Calendar getCalendarService() throws IOException { Credential credential = authorize(); return new com.google.api.services.calendar.Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build(); } } <file_sep>/at.am.googlecalendarexporter.apiwrapper/src/at/am/googlecalendar/template/XMLCalendarTemplate.java package at.am.googlecalendar.template; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.ui.IMemento; import org.eclipse.ui.WorkbenchException; import org.eclipse.ui.XMLMemento; import at.am.common.logging.LogFactory; import at.am.googlecalendar.GoogleCalendarEvent; public class XMLCalendarTemplate { private static final Logger log = LogFactory.makeLogger(); private final InputStream template; List<GoogleCalendarEvent> events; public XMLCalendarTemplate(InputStream template, List<GoogleCalendarEvent> events) { this.template = template; this.events = events; } public String parseTemplate() { StringBuilder builder = new StringBuilder(); boolean allEvents = false; try { XMLMemento memento = XMLMemento.createReadRoot(new InputStreamReader(template, "UTF-8")); IMemento titleMemento = memento.getChild("titel"); if(titleMemento.getChild("kalender") != null && events.size() > 0){ builder.append(events.get(0).getCalendarName()); } builder.append(titleMemento.getTextData()); builder.append(memento.getChild("beschreibung").getTextData()); IMemento evs = memento.getChild("termine"); if (evs != null) { allEvents = true; } IMemento[] eventDetails = evs.getChild("termin").getChildren(); for (GoogleCalendarEvent event : events) { for (IMemento mem : eventDetails) { switch (mem.getType()) { case "datum": builder.append(getDateString(event.getStartDate(), mem.getString("format"))); builder.append(mem.getTextData()); break; case "startzeit": if (event.isAllDayEvent()) { builder.append("ganztägig"); } else { builder.append(getDateString(event.getStartDate(), mem.getString("format"))); } builder.append(mem.getTextData()); break; case "endzeit": if (!event.isAllDayEvent()) { builder.append(getDateString(event.getEndDate(), mem.getString("format"))); } builder.append(mem.getTextData()); break; case "name": builder.append(event.getName()); builder.append(mem.getTextData()); break; default: break; } } if (!allEvents) { break; } } builder.append(memento.getChild("ende").getTextData()); } catch (WorkbenchException | UnsupportedEncodingException e) { log.log(Level.SEVERE, "cannot parse XML template", e); } return builder.toString(); } private String getDateString(long date, String format) { SimpleDateFormat sDF = new SimpleDateFormat(format); return sDF.format(new Date(date)); } } <file_sep>/at.am.googlecalendarexporter.apiwrapper/build.properties source.. = src/ output.. = bin/ bin.includes = META-INF/,\ .,\ libs/commons-logging-1.1.1.jar,\ libs/google-api-client-1.20.0.jar,\ libs/google-api-client-android-1.20.0.jar,\ libs/google-api-client-appengine-1.20.0.jar,\ libs/google-api-client-gson-1.20.0.jar,\ libs/google-api-client-jackson2-1.20.0.jar,\ libs/google-api-client-java6-1.20.0.jar,\ libs/google-api-client-servlet-1.20.0.jar,\ libs/google-api-services-calendar-v3-rev135-1.20.0.jar,\ libs/google-http-client-1.20.0.jar,\ libs/google-http-client-android-1.20.0.jar,\ libs/google-http-client-appengine-1.20.0.jar,\ libs/google-http-client-gson-1.20.0.jar,\ libs/google-http-client-jackson2-1.20.0.jar,\ libs/google-http-client-jdo-1.20.0.jar,\ libs/google-oauth-client-1.20.0.jar,\ libs/google-oauth-client-appengine-1.20.0.jar,\ libs/google-oauth-client-java6-1.20.0.jar,\ libs/google-oauth-client-jetty-1.20.0.jar,\ libs/google-oauth-client-servlet-1.20.0.jar,\ libs/gson-2.1.jar,\ libs/httpclient-4.0.1.jar,\ libs/httpcore-4.0.1.jar,\ libs/jackson-core-2.1.3.jar,\ libs/javax.servlet.jar,\ libs/jdo2-api-2.3-eb.jar,\ libs/jetty-6.1.26.jar,\ libs/jetty-util-6.1.26.jar,\ libs/jsr305-1.3.9.jar,\ libs/org.mortbay.jetty.jar,\ libs/transaction-api-1.1.jar src.includes = libs/,\ libs-sources/
24ca405bfe1b7af1f5cbd493810cf04e2d24328e
[ "Java", "Maven POM", "INI" ]
4
Maven POM
kingalois/calendarexport
7b5f540ce1cb759c2075fa7de3c3e499d5222c75
6aa97058c566d2c4088d97f0f611ada0b59882c7
refs/heads/master
<repo_name>anya-x/android-eservices-staticfragmenttabs<file_sep>/app/src/main/java/android/eservices/staticfragmenttabs/FragmentOne.java package android.eservices.staticfragmenttabs; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.fragment.app.Fragment; //TODO : fix this fragment so it works :) //Once it's done, then create a second fragment with the other layout public class FragmentOne extends Fragment { public static final String TAB_NAME = "ADD TO COUNTER"; public FragmentOne() { //TODO } public static FragmentOne newInstance() { //TODO return null; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //TODO return null; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void onStart() { super.onStart(); } //TODO add listener to button and transmit the information to parent Activity //TODO read the Android doc, as suggested, to do it the right way } <file_sep>/app/src/main/java/android/eservices/staticfragmenttabs/MainActivity.java package android.eservices.staticfragmenttabs; import android.os.Bundle; import android.widget.TextView; import androidx.fragment.app.FragmentActivity; import androidx.viewpager2.widget.ViewPager2; import com.google.android.material.tabs.TabLayout; public class MainActivity extends FragmentActivity { private ViewPager2 viewPager; private TabLayout tabLayout; private int currentCounter; private TextView counterTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setupViewPagerAndTabs(); } //TODO fill the method to get view references and initialize viewpager to display our fragments private void setupViewPagerAndTabs() { //TODO we want two fragments with layouts : fragment_one, fragment_two. //TODO set adapter to viewpager and handle tragment change inside //viewpager.setAdapter(...); //TabLayoutMediator tabLayoutMediator... } //TODO : increment and decrement counter, use the already provided String ressource (see strings.xml) }
005794371a37acf15dbdc27fc6361fed25a40859
[ "Java" ]
2
Java
anya-x/android-eservices-staticfragmenttabs
65d3a528d9eb82a9e06bb5beb8dcec2b41998270
3bd6ce2c72a325e80ea9ba697987b18ec3b70feb
refs/heads/master
<repo_name>YijunSu/Gradient-descent-algorithms<file_sep>/GD.py import numpy as np import random def train_BGD(x, y, alpha, theta, max_iters, epsilon): """ 批量梯度下降算法 x: 训练集, y: 标签, theta:参数向量 alpha: 学习率, max_iters: 最大迭代次数 epsilon:阈值 """ m, _ = np.shape(x) for i in range(max_iters): d_theta = (1./m)* np.dot(np.transpose(x), np.dot(x, theta)-y) #用矩阵法对所有样本进行梯度求和 theta = theta - alpha* d_theta return theta def train_SGD(x, trainData_y, alpha, theta, max_iters, epsilon): """ 随机梯度下降算法 x: 训练集, y: 标签, theta:参数向量 alpha: 学习率, max_iters: 最大迭代次数 epsilon:阈值 """ m, _ = np.shape(x) x_index = [i for i in range(m)] #取得x的索引 for i in range(max_iters): index = random.sample(x_index, 1) #从x中随机抽取一个样本的索引 d_theta = np.dot(np.transpose(x[index]), np.dot(x[index], theta)-y[index][0]) #用一个样本进行梯度更新 theta = theta - alpha* d_theta return theta def train_MBGD(x, trainData_y, alpha, theta, max_iters, epsilon): """ 小批量梯度下降算法 x: 训练集, y: 标签, theta:参数向量 alpha: 学习率, max_iters: 最大迭代次数 epsilon:阈值 """ m, _ = np.shape(x) minibatch_size = 2 for i in range(max_iters): for j in range(0, m, minibatch_size): for k in range(j, j+minibatch_size-1, 1):#用minibatch_size个样本进行梯度更新 d_theta = np.dot(np.transpose(x[k]), np.dot(x[k], theta)-y[k][0]) theta = theta - alpha* (1./minibatch_size)* d_theta return theta trainData_x = np.array([[1.1, 1.5], [1.3, 1.9], [1.5, 2.3], [1.7, 2.7], [1.9, 3.1], [2.1, 3.5], [2.3, 3.9], [2.5, 4.3], [2.7, 4.7],[2.9, 5.1]]) trainData_y = np.array([2.5,3.2,3.9,4.6,5.3,6,6.7,7.4,8.1,8.8]) m, n = np.shape(trainData_x) #获取数据集样本大小 x0 = np.ones((m,1)) #加入x0=1 x = np.hstack((x0,trainData_x)) #trainData_x中加入x0=1维 y = trainData_y.reshape(m, 1) #parameters setting alpha = 0.01 #设置学习率 theta = np.ones(n+1) #初始化参数 #两种终止条件 max_iters = 100000 #设置最大迭代次数(防止死循环) epsilon = 1e-4 #收敛阈值设置 BGD_theta = train_BGD(x, trainData_y, alpha, theta, max_iters, epsilon) print ("BGD_theta", BGD_theta) SGD_theta = train_SGD(x, trainData_y, alpha, theta, max_iters, epsilon) print ("SGD_theta", SGD_theta) MBGD_theta = train_MBGD(x, trainData_y, alpha, theta, max_iters, epsilon) print ("MBGD_theta", MBGD_theta)<file_sep>/README.md # Gradient-descent-algorithms implement some gradient descent algorithms 具体文章在我的主页:https://yijunsu.github.io/2018/08/27/2018-08-27-Gradient%20Descent/
64b160afe4d316dbbe97cbe5b58ef9f4f80fcaaf
[ "Markdown", "Python" ]
2
Python
YijunSu/Gradient-descent-algorithms
b0dac751b8b6a420f0c192611a42d2758ad622a9
3068eeb7ccc6bf0a13816fd6edf009a0497bd748
refs/heads/master
<repo_name>surajtamang/playnepal<file_sep>/app/controllers/Login.java package controllers; import play.*; import play.mvc.*; import play.data.validation.*; import play.libs.*; import play.cache.*; import java.util.*; import models.*; public class Login extends Controller { @Before static void addUser() { Member user = connected(); if(user != null) { renderArgs.put("user", user); } } static Member connected() { if(renderArgs.get("user") != null) { return renderArgs.get("user", Member.class); } String username = session.get("user"); if(username != null) { return Member.find("byUsername", username).first(); } return null; } public static void index() { render(); } public static void signin(String username, String password) { Member user = Member.find("byUsernameAndPassword", username, password).first(); if(user != null) { session.put("user", user.username); flash.success("Welcome, " + user.name); Application.index(); } // Oops flash.put("username", username); flash.error("Invalid username or password..."); Application.index(); } public static void signout() { session.clear(); Application.index(); } public static void signup() { String randomID = Codec.UUID(); render(randomID); } public static void captcha(String id) { Images.Captcha captcha = Images.captcha(); String code = captcha.getText("#EEE"); Cache.set(id, code, "30mn"); renderBinary(captcha); } public static void saveMember(@Valid Member user, @Required(message="Please type the code") String verifyPassword, @Required(message="Please type the code") String code, String randomID) { validation.required(verifyPassword); validation.equals(verifyPassword, user.password).message("Your password doesn't match"); if(!Play.id.equals("test")) { validation.equals(code, Cache.get(randomID)).message("Invalid code. Please type it again"); } if(validation.hasErrors()) { render("@signup", user, verifyPassword, randomID); } user.create(); Cache.delete(randomID); Application.index(); } } <file_sep>/app/models/Task.java package models; import java.util.*; import javax.persistence.*; import play.db.jpa.*; import play.data.validation.*; @Entity public class Task extends Model { @Required public String title; @Required @ManyToOne public Member member; public Date currentDate; public Task(String title, Member member){ this.title = title; this.member = member; this.currentDate = new Date(); } }<file_sep>/README.md play! Nepal ========= play! Nepal is the Sample Application to demonstrate Play Framework http://playnepal.herokuapp.com
99317cbd499413499007413d4bb4c921b473cd00
[ "Markdown", "Java" ]
3
Java
surajtamang/playnepal
2886ed91111f72ce06ad1b09294116e6c09c605b
2b911b7304a7d33b1b5582ceae53318577996e8c
refs/heads/master
<repo_name>llyt/frontend-project-lvl1<file_sep>/Makefile install: npm install start: sudo npx babel-node src/bin/brain-games.js publish: npm publish --dry-run lint: npx eslint . even: sudo npx babel-node src/bin/brain-even.js calc: sudo npx babel-node src/bin/brain-calc.js gcd: sudo npx babel-node src/bin/brain-gcd.js progress: sudo npx babel-node src/bin/brain-progression.js prime: sudo npx babel-node src/bin/brain-prime.js <file_sep>/src/games/gcd.js import { cons } from '@hexlet/pairs'; import engine from '..'; import genRandInt from '../randomInt'; const description = 'Find the greatest common divisor of given numbers.'; const getGcd = (number1, number2) => { let x = number1; let y = number2; while (y) { const temp = y; y = x % y; x = temp; } return x; }; const generateQuestionAnswer = () => { const num1 = genRandInt(1, 100); const num2 = genRandInt(1, 100); const question = `${num1} ${num2}`; const answer = getGcd(num1, num2); return cons(question, String(answer)); }; export default () => engine(description, generateQuestionAnswer); <file_sep>/README.md # frontend-project-lvl1 [![Maintainability](https://api.codeclimate.com/v1/badges/784f1c572917c8599641/maintainability)](https://codeclimate.com/github/llyt/frontend-project-lvl1/maintainability) [![Build Status](https://travis-ci.org/llyt/frontend-project-lvl1.svg?branch=master)](https://travis-ci.org/llyt/frontend-project-lvl1) ## Setup ```sh $ git clone https://github.com/llyt/frontend-project-lvl1.git ``` ```sh $ make install ``` ```sh $ make publish ``` ```sh $ npm link ``` ## Even Answer "yes" if number even otherwise answer "no". ```sh $ brain-even ``` [![asciicast](https://asciinema.org/a/QkjSvYM69RxMCTQbrgLiwmyeL.svg)](https://asciinema.org/a/QkjSvYM69RxMCTQbrgLiwmyeL) ## Calc What is the result of the expression? ```sh $ brain-calc ``` [![asciicast](https://asciinema.org/a/vzRTr2CV7CVxBxnyT0a8DLf3r.svg)](https://asciinema.org/a/vzRTr2CV7CVxBxnyT0a8DLf3r) ## Gcd Find the greatest common divisor of given numbers. ```sh $ brain-gcd ``` [![asciicast](https://asciinema.org/a/tYuwcadpBNDM2muwzeQYoha1G.svg)](https://asciinema.org/a/tYuwcadpBNDM2muwzeQYoha1G) ## Progress What number is missing in the progression? ```sh $ brain-progress ``` [![asciicast](https://asciinema.org/a/yWhOWn99Nejaf88cUIQbR8qbf.svg)](https://asciinema.org/a/yWhOWn99Nejaf88cUIQbR8qbf) ## Prime Answer "yes" if given number is prime. Otherwise answer "no". ```sh $ brain-prime ``` [![asciicast](https://asciinema.org/a/iSIOpPsUlXLh1SRSAPR7duBJH.svg)](https://asciinema.org/a/iSIOpPsUlXLh1SRSAPR7duBJH) <file_sep>/src/games/progression.js import { cons } from '@hexlet/pairs'; import engine from '..'; import genRandInt from '../randomInt'; const description = 'What number is missing in the progression?'; const progressionLength = 12; const getQuestion = (start, length, diff, missingElementPosition) => { let progression = ''; for (let i = 0; i < length; i += 1) { let current = start + diff * i; if (i === missingElementPosition) { current = '..'; } progression = `${progression} ${current}`; } return progression; }; const generateQuestionAnswer = () => { const start = genRandInt(1, 100); const diffrence = genRandInt(1, 10); const missingElementPosition = genRandInt(0, progressionLength - 1); const question = getQuestion(start, progressionLength, diffrence, missingElementPosition); const answer = start + diffrence * missingElementPosition; return cons(question, String(answer)); }; export default () => engine(description, generateQuestionAnswer); <file_sep>/src/bin/brain-calc.js #!/usr/bin/env node import calculator from '../games/calc'; calculator(); <file_sep>/src/games/calc.js import { cons } from '@hexlet/pairs'; import engine from '..'; import genRandInt from '../randomInt'; const description = 'What is the result of the expression?'; const operations = '+-*/'; const generateQuestionAnswer = () => { const num1 = genRandInt(20, 50); const num2 = genRandInt(1, 10); const operation = operations[genRandInt(0, operations.length - 1)]; const question = `${num1} ${operation} ${num2}`; let answer; switch (operation) { case '+': answer = num1 + num2; break; case '-': answer = num1 - num2; break; case '*': answer = num1 * num2; break; case '/': answer = num1 / num2; break; default: answer = null; } return cons(question, String(answer)); }; export default () => engine(description, generateQuestionAnswer);
e74a63492b7031d876f34794b680b5d87d8bfb2c
[ "JavaScript", "Makefile", "Markdown" ]
6
Makefile
llyt/frontend-project-lvl1
1f24ccca40bc46ea95be7f405689b12d40f9f13b
975ca8bbbc1b592756d4d1aaab93b17080e901f4
refs/heads/master
<file_sep><?php /** * Created by PhpStorm. * User: 1418349 * Date: 07/03/2016 * Time: 09:38 */ echo "Hello World"; ?>
db8eb8b186ed7c91b987a2fd14c53b53c0cba7d1
[ "PHP" ]
1
PHP
uchejudeegbue/Design
a70eb60b80132922ff56d067443c9d7f7c4ff4b3
00c7463d804dd740fea0cae8b7e09d26335f5954
refs/heads/master
<repo_name>fauzirifky/csgraph_editor<file_sep>/app/info.js /** * @author tpan496 * Script that deals with the information panel on the right. */ var paperString = "1. This editor is best suited for creating mathematical graphs.<br/> 2. Supports ctrl-c/ctrl-v operations on node and labels. <br/>3. Save your graph either as PNG or XML file for future edits." var nodeString = "Node object represents a vertex in the graph. Drag from the green center from the node to form an edge with another one."; var edgeString = "Edge object represents an edge in the graph. You can toggle on/off its arrrow from 'enable directed'."; var labelString = "Label object allows you to create text on the paper. Note that it cannot be connected via any means."; /** * Displays info of the selected object * @param {selected object} node */ var displayInfo = function (node) { clearBoard(); $('.clickedit').hide(); elementInfo.html(node.getAttribute('class')); if (isNode(node)) { xInfo.html(node.getAttribute('position-x')); xInfo.parent().show(); yInfo.html(node.getAttribute('position-y')); yInfo.parent().show(); idInfo.html(node.getAttribute('id')); idInfo.parent().show(); radiusInfo.html(node.children[0].getAttribute('radius')); radiusInfo.parent().show(); guideInfo.html(nodeString); selfLoopButton.show(); terminalButton.show(); if(node.children[3].getAttribute('visibility') == 'hidden'){ selfLoopButton.css('background', '#7a7a7a'); }else{ selfLoopButton.css('background', 'rgb(6, 218, 94)'); } if(node.children[4].getAttribute('visibility') == 'hidden'){ terminalButton.css('background', '#7a7a7a'); }else{ terminalButton.css('background', 'rgb(6, 218, 94)'); } } else if (isEdge(node)) { fromInfo.html(node.getAttribute('v1')); fromInfo.parent().show(); toInfo.html(node.getAttribute('v2')); toInfo.parent().show(); node.setAttribute('stroke-dasharray', [5, 5]); node.setAttribute('stroke', 'rgb(0,122,255)'); node.parentElement.children[1].setAttribute('fill', 'rgb(0,122,255)'); guideInfo.html(edgeString); } else if (isLabel(node)) { xInfo.html(node.getAttribute('position-x')); xInfo.parent().show(); yInfo.html(node.getAttribute('position-y')); yInfo.parent().show(); textInfo.html(node.children[0].textContent); textInfo.parent().show(); textSizeInfo.html(node.children[0].getAttribute('font-size')); textSizeInfo.parent().show(); guideInfo.html(labelString); return; } if (node.children[1]) { if (node.children[1].getAttribute('class') == 'text') { textInfo.html(node.children[1].textContent); textInfo.parent().show(); textSizeInfo.html(node.children[1].getAttribute('font-size')); textSizeInfo.parent().show(); } } }; /** * Displays x,y information of object * @param {object} node */ var displayXY = function(node) { if (isNode(node)) { xInfo.html(node.getAttribute('position-x')); xInfo.parent().show(); yInfo.html(node.getAttribute('position-y')); yInfo.parent().show(); } else if (isEdge(node)) { } else if (isLabel(node)) { xInfo.html(node.getAttribute('position-x')); xInfo.parent().show(); yInfo.html(node.getAttribute('position-y')); yInfo.parent().show(); } }; /** * Displays information of board */ var displayBoard = function () { elementInfo.html('paper'); clearBoard(); directedOnButton.show(); gridOnButton.show(); guideInfo.html(paperString); }; /** * Clears display information */ var clearBoard = function () { radiusInfo.parent().hide(); idInfo.parent().hide(); fromInfo.parent().hide(); toInfo.parent().hide(); textInfo.parent().hide(); textSizeInfo.parent().hide(); xInfo.parent().hide(); yInfo.parent().hide(); directedOnButton.hide(); gridOnButton.hide(); selfLoopButton.hide(); terminalButton.hide(); }; <file_sep>/README.md # CS Graph Diagram Editor Javascript web app for creating mathematical/computer science graph diagrams. Support basic shape manipulations(translation, scaling), edge tracking for graphs, PNG/XML export. <br />The app is inside 'app' folder, the rest being backend related files. <br />External libraries: jQuery, [jQueryHotKeys](https://github.com/jeresig/jquery.hotkeys), [saveSvgAsPng](https://github.com/exupero/saveSvgAsPng) <br />Site: [csgraph.io](https://csgraph.io) ![alt text](screenshot.png) ## Use Create nodes(vertices)/labels from left-side tool bar. Connect nodes by draggin the centered green button inside the node to targeted node. Once nodes are connected you can move them freely around as the edges would follow their connected vertices. You can also change the detailed paratemers of objects from the right-hand-side information panel. ## Note Due to transform-origin different implementations in browsers, scaling is not yet supported in Safari. It should work with latest version of Chrome/FireFox/Edge <file_sep>/app/math.js /** * @author tpan496 * Script that covers mathematical operations. */ /** * Returns a random number in [min,max] * @param {minimum} min * @param {maximum} max */ var randomRange = function (min, max) { return Math.random() * (max - min) + min; }; /** * Returns the distance between a and b, but * only in terms of horizontal one * @param {point a} a * @param {point b} b */ var dist = function (a, b) { var dx = a[0] - b[0]; var dy = a[1] - b[1]; var mult = 1; if (dx > 0 && dy > 0) { mult = -1; } return Math.sqrt(dx * dx + dx * dx) * mult; }; /** * Returns the distance between a and b * @param {point a} a * @param {point b} b */ var dist2 = function (a, b) { var dx = a[0] - b[0]; var dy = a[1] - b[1]; return Math.sqrt(dx * dx + dy * dy); }; /** * Returns the transformation matrix of object * @param {object} x */ var getMatrix = function (x) { var matrix = x.getAttribute("transform").slice(7, -1).split(' '); for (var i = 0; i < 6; i++) { matrix[i] = parseFloat(matrix[i]); }; return matrix; }; /** * Turns the matrix into a string * @param {matrix} m */ var matrixToString = function (m) { return "matrix(" + m.join(' ') + ")"; }; /** * Returns the length of a vector * @param {2d vector} v */ var absoluteLength = function (v) { return Math.sqrt(v[0] * v[0] + v[1] * v[1]); }; /** * Updates x,y position of object * @param {object} x * @param {horizontal shift} dx * @param {vertical shift} dy */ var updateXY = function (x, dx, dy) { var prevX = getX(x); var prevY = getY(x); x.setAttribute("position-x", prevX + dx); x.setAttribute("position-y", prevY + dy); }; /** * Updates radius of object * @param {object} x * @param {horizontal shift} dx */ var updateRadius = function (x, dx) { var r = getRadius(x); x.setAttribute("radius", r + dx); }; /** * Returns x position of object * @param {object} x */ var getX = function (x) { return parseFloat(x.getAttribute("position-x")); }; /** * Returns y position of object * @param {object} x */ var getY = function (x) { return parseFloat(x.getAttribute("position-y")); }; /** * Returns the absolute x position of object * @param {object} x */ var getAbsoluteX = function (x) { var currentX = getX(x); var originX = parseFloat(x.getAttribute("origin-x")); return currentX - originX; }; /** * Returns the absolute y position of object * @param {object} x */ var getAbsoluteY = function (x) { var currentY = getY(x); var originY = parseFloat(x.getAttribute("origin-y")); return currentY - originY; }; /** * Returns the current radius of object * @param {object} x */ var getRadius = function (x) { return parseFloat(x.getAttribute("radius")); }; /** * Returns the original radius of object * @param {object} x */ var getBaseRadius = function (x) { return parseFloat(x.getAttribute("r")); }; /** * Re-position an edge accroding to two nodes * @param {edge} edge * @param {arrow head} head * @param {out node} node1 * @param {in node} node2 */ var reshapeEdge = function (edge, head, node1, node2) { var r1x = getX(node1); var r1y = getY(node1); var r1 = node1.children[0].getAttribute('radius'); var r2x = getX(node2); var r2y = getY(node2); var r2 = node2.children[0].getAttribute('radius'); var d = Math.abs(dist2([r1x, r1y], [r2x, r2y])); var dx = Math.abs(r1x - r2x); var dy = Math.abs(r1y - r2y); var sina = d == 0 ? 0 : dy / d; var cosa = d == 0 ? 0 : dx / d; var x1, x2, y1, y2 = 0; if (r1x < r2x) { x1 = r1x + r1 * cosa; x2 = r2x - r2 * cosa; } else { x1 = r1x - r1 * cosa; x2 = r2x + r2 * cosa; } if (r1y < r2y) { y1 = r1y + r1 * sina; y2 = r2y - r2 * sina; } else { y1 = r1y - r1 * sina; y2 = r2y + r2 * sina; } edge.setAttribute('x1', x1); edge.setAttribute('x2', x2); edge.setAttribute('y1', y1); edge.setAttribute('y2', y2); if (!head) { return; } // arrowhead var a = 15; var theta = Math.acos(dx / d) - Math.PI / 6; var gamma = Math.PI - theta - Math.PI / 3; var xLeft, yLeft, xRight, yRight; if (x1 < x2) { xLeft = x2 - a * Math.abs(Math.cos(theta)); if (gamma < Math.PI / 2) { xRight = x2 + a * Math.abs(Math.cos(gamma)); } else { xRight = x2 - a * Math.abs(Math.cos(gamma)); } } else { xLeft = x2 + a * Math.abs(Math.cos(theta)); if (gamma < Math.PI / 2) { xRight = x2 - a * Math.abs(Math.cos(gamma)); } else { xRight = x2 + a * Math.abs(Math.cos(gamma)); } } if (y1 < y2) { yLeft = y2 - a * Math.sin(theta); yRight = y2 - a * Math.sin(gamma); } else { yLeft = y2 + a * Math.sin(theta); yRight = y2 + a * Math.sin(gamma); } var array = arr = [[xLeft, yLeft], [xRight, yRight], [x2, y2]]; head.setAttribute('points', ''); for (value of array) { var point = svg.createSVGPoint(); point.x = value[0]; point.y = value[1]; head.points.appendItem(point); } }; /** * Reposition all the edges related to the * object node * @param {object node} x */ var reshapeEdges = function (x) { var id = x.getAttribute('id'); var edges = getEdges(id); var l = edges.length; for (i = 0; i < l; i++) { var edge = edges[i]; var v1 = edge.children[0].getAttribute('v1'); var v2 = edge.children[0].getAttribute('v2'); reshapeEdge(edge.children[0], edge.children[1], V[v1], V[v2]); } };<file_sep>/app/misc.js /** * @author tpan496 * Script that deals with button events in the right-hand-side * info panels and a few button events on the left(export, load). */ var gridOn = true; var directedOn = true; /** * Toggles on/off of grid. * @param {mouse event} target */ var toggleGrid = function (target) { if (gridOn) { target.css('background', '#7a7a7a'); gridOn = false; $('#content').hide(); } else { target.css('background', 'rgb(6, 218, 94)'); gridOn = true; $('#content').show(); } }; /** * Toggles on/off of direction of graph. * @param {mouse event} target */ var toggleDirected = function (target) { if (directedOn) { target.css('background', '#7a7a7a'); directedOn = false; for (v of E_shape) { for (e of v) { e.children[1].setAttribute('visibility', 'hidden'); } } } else { target.css('background', 'rgb(6, 218, 94)'); directedOn = true; for (v of E_shape) { for (e of v) { e.children[1].setAttribute('visibility', 'visible'); } } } }; /** * Export PNG */ var exportPNG = function () { var foreigns = []; for (child of svg.children) { if (child.getAttribute('class') == 'label') { var foreign = child.children[2]; child.removeChild(foreign); foreigns.push(foreign); } } saveSvgAsPng(svg, "diagram.png"); for (child of svg.children) { if (child.getAttribute('class') == 'label') { child.appendChild(foreigns.shift()); } } }; /** * Save as XML */ var saveXML = function () { turnOffSelectedElementScaler(); // Get svg source. var serializer = new XMLSerializer(); var source = serializer.serializeToString(svg); // Add name spaces. if (!source.match(/^<svg[^>]+xmlns="http\:\/\/www\.w3\.org\/2000\/svg"/)) { source = source.replace(/^<svg/, '<svg xmlns="http://www.w3.org/2000/svg"'); } if (!source.match(/^<svg[^>]+"http\:\/\/www\.w3\.org\/1999\/xlink"/)) { source = source.replace(/^<svg/, '<svg xmlns:xlink="http://www.w3.org/1999/xlink"'); } // Add xml declaration source = '<?xml version="1.0" standalone="no"?>\r\n' + source; // Convert svg source to URI data scheme. var url = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(source); var a = document.createElement('a'); a.href = url; a.download = 'diagram.xml'; a.click(); }; /** * Load XML from external source */ var loadXML = function () { var input = document.createElement('input'); input.type = 'file'; input.id = 'file'; input.accept = '.xml'; input.onchange = function (e) { var loadedXML = input.files[0]; var type = loadedXML.name.split('.')[1]; if (!type || type != 'xml') { alert('Incorrect file format'); return; } var reader = new FileReader(); reader.onload = function () { var dataURL = reader.result; delete svg; var content = $('#content'); $('#paper').html(dataURL).append(content) .find('#box').appendTo($('#paper'));; svg = $('svg')[0]; svg.setAttribute('z-index', -1); generateGraphFromXml(); $('svg').click(function () { if (selectedElement != 0 && !mouseOverNode) { turnOffSelectedElementScaler(); } }); }; reader.readAsText(loadedXML); }; if (document.createEvent) { var evt = document.createEvent("MouseEvents"); evt.initEvent("click", true, false); input.dispatchEvent(evt); } }; /** * Toggle on/off self-loop indicator for a node * @param {button} target * @param {node object} e */ var toggleSelfLoop = function(target, e){ if(e.children[3].getAttribute('visibility') == 'hidden'){ e.children[3].setAttribute('visibility', 'visible'); target.css('background', 'rgb(6, 218, 94)'); }else{ e.children[3].setAttribute('visibility', 'hidden'); target.css('background', '#7a7a7a'); } }; /** * Toggle on/off terminal indicator for a node * @param {button} target * @param {node object} e */ var toggleTerminal = function(target, e){ if(e.children[4].getAttribute('visibility') == 'hidden'){ e.children[4].setAttribute('visibility', 'visible'); target.css('background', 'rgb(6, 218, 94)'); }else{ e.children[4].setAttribute('visibility', 'hidden'); target.css('background', '#7a7a7a'); } };<file_sep>/app/shape.js /** * @author tpan496 * Script that deals with basic shape manipulations. */ var svgns = "http://www.w3.org/2000/svg" /** * Draws a circle * @param {x position} x * @param {y position} y * @param {radius} radius * @param {fill color} fill * @param {stroke color} stroke * @param {stroke width} strokeWidth */ var drawCircle = function (x, y, radius, fill, stroke, strokeWidth) { var circle = document.createElementNS(svgns, 'circle'); circle.setAttribute('cx', x); circle.setAttribute('cy', y); circle.setAttribute('r', radius); circle.setAttribute('fill', fill); circle.setAttribute('stroke', stroke); circle.setAttribute('stroke-width', strokeWidth); var tOrigin = x+'px'+' '+y+'px'; circle.setAttribute('transform-origin', tOrigin); circle.setAttribute('transform', 'matrix(1 0 0 1 0 0)'); circle.style.MozTransformOrigin = tOrigin; circle.style.webkitTransformOrigin = tOrigin; circle.style.transformOrigin = tOrigin; circle.style.msTransformOrigin = tOrigin; circle.setAttribute('vector-effect', 'non-scaling-stroke'); circle.setAttribute('position-x', x); circle.setAttribute('position-y', y); circle.setAttribute('origin-x', x); circle.setAttribute('origin-y', y); circle.setAttribute('radius', radius); return circle; }; /** * Draws a rectangle at given position * @param {x position} x * @param {y position} y * @param {width} w * @param {height} h */ var drawRect = function (x, y, w, h) { var rect = document.createElementNS(svgns, 'rect'); rect.setAttributeNS(null, 'x', x); rect.setAttributeNS(null, 'y', y); rect.setAttributeNS(null, 'width', w); rect.setAttributeNS(null, 'height', h); rect.setAttribute('stroke', 'rgb(0,122,255)'); rect.setAttribute('fill', 'transparent'); rect.setAttribute('stroke-dasharray', [2, 2]); rect.setAttribute('stroke-width', 2); return rect; }; /** * Draws a line from point 1 to point 2 * @param {x1 position} x1 * @param {y1 position} y1 * @param {x2 position} x2 * @param {y2 position} y2 * @param {width} w * @param {color} color */ var drawLine = function (x1, y1, x2, y2, w, color) { var line = document.createElementNS(svgns, 'line'); line.setAttribute('x1', x1); line.setAttribute('x2', x2); line.setAttribute('y1', y1); line.setAttribute('y2', y2); line.setAttribute('stroke', color); line.setAttribute('stroke-width', w); line.setAttribute('transform', 'matrix(1 0 0 1 0 0)'); var xm = (x1+x2)/2, ym = (y1+y2)/2; var tOrigin = xm+'px'+' '+ym+'px'; line.setAttribute('vector-effect', 'non-scaling-stroke'); line.setAttribute('transform-origin', tOrigin); line.style.MozTransformOrigin = tOrigin; line.style.webkitTransformOrigin = tOrigin; line.style.transformOrigin = tOrigin; line.style.msTransformOrigin = tOrigin; line.setAttribute('position-x', xm); line.setAttribute('position-y', ym); line.setAttribute('origin-x', xm); line.setAttribute('origin-y', ym); return line; }; /** * Draws a dashed line from point 1 to point 2 * @param {x1 position} x1 * @param {y1 position} y1 * @param {x2 position} x2 * @param {y2 position} y2 * @param {dash array} array * @param {width} w * @param {color} color */ var drawDashedLine = function (x1, y1, x2, y2, array, w, color) { var line = document.createElementNS(svgns, 'line'); line.setAttribute('x1', x1); line.setAttribute('x2', x2); line.setAttribute('y1', y1); line.setAttribute('y2', y2); line.setAttribute('stroke', color); line.setAttribute('stroke-width', w); line.setAttribute('stroke-dasharray', array); line.setAttribute('transform', 'matrix(1 0 0 1 0 0)'); var xm = (x1+x2)/2, ym = (y1+y2)/2; var tOrigin = xm+'px'+' '+ym+'px'; line.setAttribute('vector-effect', 'non-scaling-stroke'); line.setAttribute('transform-origin', tOrigin); line.style.MozTransformOrigin = tOrigin; line.style.webkitTransformOrigin = tOrigin; line.style.transformOrigin = tOrigin; line.style.msTransformOrigin = tOrigin; line.setAttribute('position-x', xm); line.setAttribute('position-y', ym); line.setAttribute('origin-x', xm); line.setAttribute('origin-y', ym); return line; }; /** * Draws a text at given position. Default text is 'text' * @param {x position} x * @param {y position} y * @param {text} t */ var drawText = function (x, y, t) { var text = document.createElementNS(svgns, 'text'); text.setAttribute('x', x); text.setAttribute('y', y); var tOrigin = x+'px'+' '+y+'px'; text.setAttribute('transform-origin', tOrigin); text.style.MozTransformOrigin = tOrigin; text.style.webkitTransformOrigin = tOrigin; text.style.transformOrigin = tOrigin; text.style.msTransformOrigin = tOrigin; text.setAttribute('text-anchor', 'middle'); text.setAttribute('font-family', 'Arial'); text.setAttribute('transform', 'matrix(1 0 0 1 0 0)'); text.setAttribute('vector-effect', 'non-scaling-stroke'); text.setAttribute('fill', 'black'); text.setAttribute('stroke-width', '0.5px'); text.setAttribute('pointer-events', 'none'); text.setAttribute('position-x', x); text.setAttribute('position-y', y); text.setAttribute('origin-x', x); text.setAttribute('origin-y', y); text.setAttribute('class', 'text'); text.setAttribute('font-size', 15); text.setAttribute('alignment-baseline', 'central'); if (t === "") { text.textContent = 'text'; } else { text.textContent = t; } return text; }; /** * Draws an arrow head at one end of edge * @param {given edge} edge */ var drawArrowHead = function (edge) { var a = 15.0; var x1 = parseFloat(edge.getAttribute('x1')); var x2 = parseFloat(edge.getAttribute('x2')); var y1 = parseFloat(edge.getAttribute('y1')); var y2 = parseFloat(edge.getAttribute('y2')); var polygon = document.createElementNS(svgns, "polygon"); svg.appendChild(polygon); var d = dist2([x1, y1], [x2, y2]); var dx = Math.abs(x1 - x2); var dy = Math.abs(y1 - y2); var theta = Math.acos(dx / d) - Math.PI / 6; var gamma = Math.PI - theta - Math.PI / 3; var xLeft, yLeft, xRight, yRight; if (x1 < x2) { xLeft = x2 - a * Math.abs(Math.cos(theta)); if (gamma < Math.PI / 2) { xRight = x2 + a * Math.abs(Math.cos(gamma)); } else { xRight = x2 - a * Math.abs(Math.cos(gamma)); } } else { xLeft = x2 + a * Math.abs(Math.cos(theta)); if (gamma < Math.PI / 2) { xRight = x2 - a * Math.abs(Math.cos(gamma)); } else { xRight = x2 + a * Math.abs(Math.cos(gamma)); } } if (y1 < y2) { yLeft = y2 - a * Math.sin(theta); yRight = y2 - a * Math.sin(gamma); } else { yLeft = y2 + a * Math.sin(theta); yRight = y2 + a * Math.sin(gamma); } var array = arr = [[xLeft, yLeft], [xRight, yRight], [x2, y2]]; for (value of array) { var point = svg.createSVGPoint(); point.x = value[0]; point.y = value[1]; polygon.points.appendItem(point); } polygon.setAttribute('class', 'arrow-head'); var tOrigin = x+'px'+' '+y+'px'; polygon.setAttribute('transform-origin', tOrigin); polygon.style.MozTransformOrigin = tOrigin; polygon.style.webkitTransformOrigin = tOrigin; polygon.style.transformOrigin = tOrigin; polygon.style.msTransformOrigin = tOrigin; polygon.setAttribute('fill', 'black'); return polygon; }; /** * Draws an input text box at given position * @param {x position} x * @param {y position} y * @param {width} w * @param {height} h */ var drawInputBox = function (x, y, w, h) { var foreign = document.createElementNS(svgns, 'foreignObject'); foreign.setAttribute('x', x); foreign.setAttribute('y', y); foreign.setAttribute('width', 100); foreign.setAttribute('height', 100); var input = document.createElement('input') input.x = x; input.y = y; input.type = 'text'; input.value = 'text'; input.style.textAlign = "center"; input.style.fontSize = "15pt"; input.size = 4; input.style.paddingTop = 0; foreign.appendChild(input); return foreign; }; /** * Draws an incomplete circle(-135 deg to 135 deg) * @param {x position} x * @param {y position} y * @param {radius} r */ var drawHalfCircle = function (x, y, r) { var g = document.createElementNS(svgns, 'g'); var path = document.createElementNS(svgns, 'path'); var R = r; var r = 15; if(R<15){ r = R*0.8; } var xx = x; var yy = y - (Math.sqrt(R*R-r*r/8)+r/Math.sqrt(2)); path.setAttribute('d', describeArc(xx,yy,r,-135,135)); path.setAttribute('fill', 'none'); path.setAttribute('stroke-width', 1.5); path.setAttribute('stroke', 'black'); var polygon = document.createElementNS(svgns, "polygon"); var x = xx - r*8/15, y = yy - r*2/15; var theta = Math.PI / 6; var gamma = Math.PI - Math.PI / 6 - Math.PI / 3; var xLeft = x - 15 * Math.cos(theta), yLeft = y + 15 * Math.sin(theta), xRight = x + 15 * Math.cos(gamma), yRight = y + 15 * Math.sin(gamma); var array = arr = [[xLeft, yLeft], [xRight, yRight], [x, y]]; for (value of array) { var point = svg.createSVGPoint(); point.x = value[0]; point.y = value[1]; polygon.points.appendItem(point); } polygon.setAttribute('class', 'arrow-head'); var tOrigin = x+'px'+' '+y+'px'; polygon.setAttribute('transform-origin', tOrigin); polygon.style.MozTransformOrigin = tOrigin; polygon.style.webkitTransformOrigin = tOrigin; polygon.style.transformOrigin = tOrigin; polygon.style.msTransformOrigin = tOrigin; polygon.setAttribute('fill', 'black'); g.appendChild(path); g.appendChild(polygon); return g; }; /** * Replace the old incomplete circle with a new one * @param {node containing this circle} node * @param {old incomplete circle} loop * @param {new x position} x * @param {new y position} y * @param {new radius} r */ var updateHalfCircle = function (node, loop, x, y, r) { var g = drawHalfCircle(x, y, r); if(loop.getAttribute('visibility') == 'hidden'){ g.setAttribute('visibility', 'hidden'); } var terminal = node.children[4]; node.removeChild(terminal); node.removeChild(loop); node.appendChild(g); node.appendChild(terminal); }; /** * Transforms to cartesian values * @param {x position} centerX * @param {y position} centerY * @param {radius} radius * @param {angle} angleInDegrees */ var polarToCartesian = function(centerX, centerY, radius, angleInDegrees) { var angleInRadians = (angleInDegrees - 90) * Math.PI / 180.0; return { x: centerX + (radius * Math.cos(angleInRadians)), y: centerY + (radius * Math.sin(angleInRadians)) }; } /** * Draws an arc * @param {x position} x * @param {y position} y * @param {radius} radius * @param {start angle} startAngle * @param {end angle} endAngle */ var describeArc = function(x, y, radius, startAngle, endAngle) { var start = polarToCartesian(x, y, radius, endAngle); var end = polarToCartesian(x, y, radius, startAngle); var largeArcFlag = endAngle - startAngle <= 180 ? "0" : "1"; var d = [ "M", start.x, start.y, "A", radius, radius, 0, largeArcFlag, 0, end.x, end.y ].join(" "); return d; }<file_sep>/app/core.js /** * @author tpan496 * Core script that deals with all the events triggered inside html. * Include events for svg, buttons, key events, and input boxes. */ // variables var svgns = "http://www.w3.org/2000/svg" var selectedElement = 0; var selectedScaler = 0; var selectedLinker = 0; var selectedEditBox = 0; var linkPointer = 0; var mouseOverNode = false; var overNode = 0; var currentX = 0; var currentY = 0; var currentMatrix = [1, 0, 0, 1, 0, 0]; var currentEditTarget = 0; var serialId = 0; var dragging = false; var linkerMouseDown = false; var editing = false; var forceAlign = false; // copy paste var copiedElement = 0; // ui infos var elementInfo; var xInfo; var yInfo; var radiusInfo; var idInfo; var fromInfo; var toInfo; var textInfo; var textSizeInfo; var guideInfo; var gridOnButton; var directedOnButton; var clearButton; var selfLoopButton; var terminalButton; /** * Called when document is loaded. Registers events triggered by * clicking buttons/spawning objects. */ $(document).ready(function () { svg = $('svg')[0]; radiusInfo = $('label#radius'); idInfo = $('label#id'); xInfo = $('label#x'); yInfo = $('label#y'); elementInfo = $('.info#element'); fromInfo = $('label#from'); toInfo = $('label#to'); textInfo = $('label#text'); textSizeInfo = $('label#text-size'); gridOnButton = $('#grid'); directedOnButton = $('#directed'); guideInfo = $('#guide'); selfLoopButton = $('#self-loop'); terminalButton = $('#terminal'); displayBoard(); // Node button for spawning nodes $('#button-circle').click(function () { var rx = parseInt(randomRange(0, 20)); var ry = parseInt(randomRange(0, 20)); var x = parseInt(svg.getBoundingClientRect().width / 2) + rx; var y = parseInt(svg.getBoundingClientRect().height / 2) + ry; var node = drawNode(x, y); svg.appendChild(node); if (selectedElement != 0) { turnOffSelectedElementIndicators(); } selectedElement = node; selectedElement.children[1].setAttribute('fill', 'rgb(175,175,175)'); currentMatrix = getMatrix(selectedElement); displayInfo(node); }); // Label button for spawning lables $('#button-label').click(function () { var rx = parseInt(randomRange(0, 20)); var ry = parseInt(randomRange(0, 20)); var x = parseInt(svg.getBoundingClientRect().width / 2) + rx; var y = parseInt(svg.getBoundingClientRect().height / 2) + ry; var label = drawLabel(x, y); svg.appendChild(label); updateLabel(label); label.children[1].setAttribute('stroke', 'rgb(0,122,255)'); if (selectedElement != 0) { turnOffSelectedElementIndicators(); } selectedElement = label; currentMatrix = getMatrix(selectedElement); displayInfo(label); }); // Save PNG button for exporting to PNG $('#button-png').click(function () { exportPNG(); }); // Save XML button for exporting to XML $('#button-xml').click(function () { saveXML(); }); // Load XML button for loading XML $('#button-load').click(function () { loadXML(); }); // Clear button for clearing the page $('#button-clear').click(function () { $('svg').html(''); serialId = 0; }); // SVG click listener $('svg').click(function () { if (selectedElement != 0 && !mouseOverNode) { turnOffSelectedElementIndicators(); } }); // Input box click/focusout event listener $('.clickedit').focusout(endInfoEdit).keyup(function (e) { if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) { endInfoEdit(e); return false; } else { return true; } }).prev().click(function () { $(this).hide(); $(this).next().show().focus(); $(this).next().val($(this).text()); editing = true; currentEditTarget = $(this).next(); }); // Enable grid button $('#grid').click(function () { toggleGrid($(this)); }); // Enable directed button $('#directed').click(function () { toggleDirected($(this)); }); // Enable self-loop button $('#self-loop').click(function () { toggleSelfLoop($(this), selectedElement); }); // Enable terminal button $('#terminal').click(function () { toggleTerminal($(this), selectedElement); }); }); /** * Turns off the additional indicators for the previous * selected element. */ var turnOffSelectedElementIndicators = function () { if (selectedElement != 0 && (isNode(selectedElement) || isEdge(selectedElement) || isLabel(selectedElement))) { var scaler = selectedElement.children[2]; if (scaler) { scaler.setAttribute("visibility", "hidden"); } if (isNode(selectedElement)) { var text = selectedElement.children[1]; if (text) { text.setAttribute('fill', 'black'); } } if (isEdge(selectedElement)) { selectedElement.setAttribute('stroke-dasharray', ''); selectedElement.setAttribute('stroke', 'black'); selectedElement.parentElement.children[1].setAttribute('fill', 'black'); } if (isLabel(selectedElement)) { selectedElement.children[1].setAttribute('stroke', 'transparent'); if (editing) { endLabelEdit(); } } selectedElement = 0; displayBoard(); } }; var editLabel = function (evt) { if (isLabel(selectedElement)) { editing = true; selectedElement.children[2].setAttribute('visibility', 'visible'); selectedElement.children[0].setAttribute('pointer-event', 'none'); selectedEditBox = selectedElement.children[2]; svg.appendChild(selectedEditBox); selectedElement.setAttribute('pointer-event', 'none'); } }; /** * Ends the editing phase for label */ var endLabelEdit = function () { if (isLabel(selectedElement)) { editing = false; if (selectedEditBox.children[0].value === '') { svg.removeChild(selectedEditBox); svg.removeChild(selectedElement); return; } selectedElement.appendChild(selectedEditBox); selectedEditBox.setAttribute('visibility', 'hidden'); selectedElement.children[0].textContent = selectedEditBox.children[0].value; selectedElement.children[0].setAttribute('pointer-event', 'all'); updateLabel(selectedElement); displayInfo(selectedElement); selectedElement.children[0].blur(); } }; /** * Updates the label after it is render * @param {label} label */ var updateLabel = function (label) { var bbox = label.children[0].getBBox(); label.children[1].setAttribute('x', bbox.x); label.children[1].setAttribute('y', bbox.y); label.children[1].setAttribute('width', bbox.width); label.children[1].setAttribute('height', bbox.height); label.children[2].setAttribute('x', getX(label) - bbox.width / 2); label.children[2].setAttribute('y', getY(label) - bbox.height / 2); label.children[2].setAttribute('width', bbox.width); label.children[2].setAttribute('height', bbox.height); label.children[2].children[0].setAttribute('x', bbox.x); label.children[2].children[0].setAttribute('y', bbox.y); label.children[2].children[0].setAttribute('size', label.children[0].textContent.length); label.children[2].children[0].value = label.children[0].textContent; }; /** * Called when the linker is selected. Draws a link pointer. * @param {mouse event} e */ var selectLinker = function (e) { e.preventDefault(); if (e.target.getAttribute("class") != "linker") { return; } selectedLinker = e.target; currentX = e.clientX; currentY = e.clientY; linkerMouseDown = true; linkPointer = drawLine(getX(selectedLinker.parentElement.parentElement), getY(selectedLinker.parentElement.parentElement), currentX, currentY, 3, 'red'); svg.appendChild(linkPointer); clearSVGEvents(); svg.setAttribute('onmousemove', 'moveLinker(evt)'); svg.setAttribute('onmouseup', 'deselectLinker(evt)'); }; /** * Called after a linker has been selected and the user is dragging * the pointer to some target. * @param {mouse event} e */ var moveLinker = function (e) { e.preventDefault(); if (linkerMouseDown) { linkPointer.setAttribute('x2', currentX); linkPointer.setAttribute('y2', currentY); if (mouseOverNode && overNode.parentElement.hasAttribute("position-x")) { linkPointer.setAttribute('x2', getX(overNode.parentElement)); linkPointer.setAttribute('y2', getY(overNode.parentElement)); } } currentX = e.clientX; currentY = e.clientY; }; /** * Called after the linker is deselcted. * @param {mouse event} e */ var deselectLinker = function (e) { e.preventDefault(); linkerMouseDown = false; if (!mouseOverNode || !(overNode.parentElement.getAttribute('class') == 'node')) { svg.removeChild(svg.lastChild); } else { var v1 = selectedLinker.parentElement.parentElement.getAttribute('id') var v2 = overNode.parentElement.getAttribute('id') if (E_out[v1].indexOf(v2) >= 0) { svg.removeChild(svg.lastChild); selectedLinker = 0; linkPointer = 0; clearSVGEvents(); return; } var arrow = document.createElementNS(svgns, 'g'); linkPointer.setAttribute('v1', v1); linkPointer.setAttribute('v2', v2); linkPointer.setAttribute('stroke', 'black'); linkPointer.setAttribute('stroke-width', 1.5); linkPointer.setAttribute('class', 'edge'); linkPointer.setAttribute('onclick', 'selectEdge(evt)'); linkPointer.setAttribute('onmouseover', 'hoverElement(evt)'); linkPointer.setAttribute('onmouseout', 'outElement(evt)'); reshapeEdge(linkPointer, 0, V[v1], V[v2]); var arrowHead = drawArrowHead(linkPointer); arrow.appendChild(linkPointer); arrow.appendChild(arrowHead); if (!directedOn) { arrowHead.setAttribute('visibility', 'hidden'); } svg.insertBefore(arrow, svg.firstChild); addEdge(v1, v2, arrow); } selectedLinker = 0; linkPointer = 0; clearSVGEvents(); }; /** * Called when an edge is selected. * @param {mouse event} e */ var selectEdge = function (e) { e.preventDefault(); clearEdit(); if (e.target.getAttribute('class') != 'edge') { return; } turnOffSelectedElementIndicators(); selectedElement = e.target; displayInfo(selectedElement); }; /** * Called when a scaler node is selected. * @param {mouse event} e */ var selectScaler = function (e) { e.preventDefault(); if (e.target.getAttribute("class") != "scale-node") { return; } dragging = true; selectedScaler = e.target; currentX = e.clientX; currentY = e.clientY; currentMatrix = selectedScaler.getAttribute("transform").slice(7, -1).split(' '); for (var i = 0; i < 6; i++) { var par = parseFloat(currentMatrix[i]); currentMatrix[i] = par; } clearSVGEvents(); svg.setAttribute('onmousemove', 'moveScaler(evt)'); svg.setAttribute('onmouseup', 'deselectElement(evt)'); }; /** * Called after a scale node has been selected, and the user * is dragging the scaler node. * @param {mouse event} e */ var moveScaler = function (e) { e.preventDefault(); var dx = e.clientX - currentX; var dy = e.clientY - currentY; var scalerId = selectedScaler.getAttribute('id'); // in case of circle var shiftDx = dx >= dy ? dx : (dx * dy >= 0 ? dy : -dy); var shiftDy = dx >= dy ? (dx * dy >= 0 ? dx : -dx) : dy; var radius = getRadius(selectedElement.children[0]); switch (scalerId) { case 'nw': if (shiftDx * shiftDy < 0) { return; } break; case 'ne': if (shiftDx * shiftDy > 0) { return; } break; case 'se': if (shiftDx * shiftDy < 0) { return; } break; case 'sw': if (shiftDx * shiftDy > 0) { return; } break; } currentMatrix[4] += shiftDx; currentMatrix[5] += shiftDy; newMatrix = "matrix(" + currentMatrix.join(' ') + ")"; updateXY(selectedScaler, shiftDx, shiftDy); selectedScaler.setAttribute('transform', newMatrix); currentX = e.clientX; currentY = e.clientY; // Scale the node according to mouse movement scale(shiftDx, shiftDy); }; /** * Called when a label has been selected. * @param {mouse event} e */ var selectLabel = function (e) { e.preventDefault(); clearEdit(); if (e.target.parentElement.getAttribute("class") != "label") { return; } if (selectedElement != e.target.parentElement) { turnOffSelectedElementIndicators(); } selectedElement = e.target.parentElement; displayInfo(selectedElement); selectedElement.children[1].setAttribute('stroke', 'rgb(0,122,255)'); currentX = e.clientX; currentY = e.clientY; currentMatrix = getMatrix(selectedElement); svg.setAttribute("onmousemove", "moveElement(evt)"); svg.setAttribute("onmouseup", "deselectElement(evt)"); }; /** * Called when a graph node is selected. * @param {mouse event} e */ var selectNode = function (e) { e.preventDefault(); clearEdit(); if (e.target.parentElement.getAttribute("class") != "node") { return; } if (selectedElement != e.target.parentElement) { turnOffSelectedElementIndicators(); } selectedElement = e.target.parentElement; displayInfo(selectedElement); selectedElement.children[1].setAttribute('fill', 'rgb(175,175,175)'); // Render scalers var scaler = selectedElement.children[2]; if (scaler.getAttribute("visibility") === "hidden") { scaler.setAttribute("visibility", "visible"); } currentX = e.clientX; currentY = e.clientY; currentMatrix = getMatrix(selectedElement); svg.setAttribute("onmousemove", "moveElement(evt)"); svg.setAttribute("onmouseup", "deselectElement(evt)"); }; /** * Called after a node/label has been selected and the user is * dragging the object. * @param {mouse event} e */ var moveElement = function (e) { e.preventDefault(); var dx = e.clientX - currentX; var dy = e.clientY - currentY; currentMatrix[4] += dx; currentMatrix[5] += dy; newMatrix = "matrix(" + currentMatrix.join(' ') + ")"; selectedElement.setAttribute('transform', newMatrix); updateXY(selectedElement, dx, dy); displayXY(selectedElement); if (isNode(selectedElement)) { reshapeEdges(selectedElement); } else if (isLabel(selectedElement)) { var foreign = selectedElement.children[2]; var bbox = selectedElement.children[0].getBBox(); foreign.setAttribute('x', getX(selectedElement) - bbox.width / 2); foreign.setAttribute('y', getY(selectedElement) - bbox.height / 2); } currentX = e.clientX; currentY = e.clientY; }; /** * Called when the user released the mouse. * @param {mouse event} evt */ var deselectElement = function (evt) { evt.preventDefault(); clearSVGEvents(); selectedScaler = 0; if (isNode(selectedElement)) { reshapeEdges(selectedElement); } }; /** * Called when the mouse is over a object * @param {mouse event} e */ var hoverElement = function (e) { mouseOverNode = true; overNode = e.target; }; /** * Called when the mouse comes out of a object * @param {mouse event} e */ var outElement = function (e) { mouseOverNode = false; overNode = 0; }; /** * Called when user is editing the pressed enter or click somewhere else * @param {mouse event} e */ var endInfoEdit = function(e) { // change selected element shape according to text if (editing) { var input = $(e.target), label = input && input.prev(); label.text(input.val() === '' ? label.textContent : input.val()); input.hide(); label.show(); var val = input.val() === '' ? '' : input.val(); var id = label.attr('id'); if (id == 'radius') { scaleTo(parseFloat(input.val())); var id = selectedElement.getAttribute('id'); var edges = getEdges(id); var l = edges.length; for (i = 0; i < l; i++) { var edge = edges[i]; var v1 = edge.children[0].getAttribute('v1'); var v2 = edge.children[0].getAttribute('v2'); reshapeEdge(edge.children[0], edge.children[1], V[v1], V[v2]); } } else if (id == 'text') { if (isNode(selectedElement)) { selectedElement.children[1].textContent = val; } else if (isLabel(selectedElement)) { selectedElement.children[0].textContent = input.val(); var bbox = selectedElement.children[0].getBBox(); selectedElement.children[1].setAttribute('x', parseFloat(selectedElement.children[0].getAttribute('x')) - bbox.width / 2); selectedElement.children[1].setAttribute('y', parseFloat(selectedElement.children[0].getAttribute('y')) - bbox.height / 2); selectedElement.children[1].setAttribute('width', bbox.width); selectedElement.children[1].setAttribute('height', bbox.height); selectedElement.children[2].children[0].value = input.val(); } } else if (id == 'text-size') { if (isNode(selectedElement)) { selectedElement.children[1].setAttribute('font-size', input.val()); } else if (isLabel(selectedElement)) { selectedElement.children[0].setAttribute('font-size', input.val()); var bbox = selectedElement.children[0].getBBox(); selectedElement.children[1].setAttribute('x', parseFloat(selectedElement.children[0].getAttribute('x')) - bbox.width / 2); selectedElement.children[1].setAttribute('y', parseFloat(selectedElement.children[0].getAttribute('y')) - bbox.height / 2); selectedElement.children[1].setAttribute('width', bbox.width); selectedElement.children[1].setAttribute('height', bbox.height); selectedElement.children[2].children[0].style.fontSize = input.val() * 0.8 + "pt"; selectedElement.children[2].children[0].height = bbox.height; selectedElement.children[0].setAttribute('pointer-event', 'all'); updateLabel(selectedElement); } } else if (id == 'x') { var newPosX = parseFloat(input.val()); var dx = newPosX - getX(selectedElement); currentMatrix[4] += dx; newMatrix = "matrix(" + currentMatrix.join(' ') + ")"; selectedElement.setAttribute('transform', newMatrix); updateXY(selectedElement, dx, 0); displayXY(selectedElement); if (isNode(selectedElement)) { reshapeEdges(selectedElement); } else if (isLabel(selectedElement)) { var foreign = selectedElement.children[2]; var bbox = selectedElement.children[0].getBBox(); foreign.setAttribute('x', getX(selectedElement) - bbox.width / 2); updateLabel(selectedElement); } } else if (id == 'y') { var newPosY = parseFloat(input.val()); var dy = newPosY - getY(selectedElement); currentMatrix[5] += dy; newMatrix = "matrix(" + currentMatrix.join(' ') + ")"; selectedElement.setAttribute('transform', newMatrix); updateXY(selectedElement, 0, dy); displayXY(selectedElement); if (isNode(selectedElement)) { reshapeEdges(selectedElement); } else if (isLabel(selectedElement)) { var foreign = selectedElement.children[2]; var bbox = selectedElement.children[0].getBBox(); foreign.setAttribute('y', getY(selectedElement) - bbox.height / 2); updateLabel(selectedElement); } } input.val(' '); } editing = false; }; /** * Called for copy event */ var copySelectedElement = function () { if (selectedElement != 0) { if (isLabel(selectedElement) || isNode(selectedElement)) { copiedElement = selectedElement; console.log('copied') } } }; /** * Called for paste event */ var pasteSelectedElement = function () { if (copiedElement != 0) { console.log('pasted'); if (isNode(copiedElement)) { var rx = randomRange(0, 20); var ry = randomRange(0, 20); var x = getX(copiedElement) + rx; var y = getY(copiedElement) + ry; var node = drawNode(x, y); svg.appendChild(node); if (selectedElement != 0) { turnOffSelectedElementIndicators(); } selectedElement = node; scaleTo(getRadius(copiedElement.children[0])); node.children[1].textContent = copiedElement.children[1].textContent; selectedElement.children[1].setAttribute('fill', 'rgb(175,175,175)'); currentMatrix = getMatrix(selectedElement); displayInfo(node); } else { var rx = randomRange(0, 20); var ry = randomRange(0, 20); var x = getX(copiedElement) + rx; var y = getY(copiedElement) + ry; var label = drawLabel(x, y); svg.appendChild(label); label.children[0].setAttribute('font-size', copiedElement.children[0].getAttribute('font-size')); label.children[1].setAttribute('stroke', 'rgb(0,122,255)'); if (selectedElement != 0) { turnOffSelectedElementIndicators(); } selectedElement = label; label.children[0].textContent = copiedElement.children[0].textContent; updateLabel(label); var bbox = label.children[0].getBBox(); label.children[1].setAttribute('x', parseFloat(label.children[0].getAttribute('x')) - bbox.width / 2); label.children[1].setAttribute('y', parseFloat(label.children[0].getAttribute('y')) - bbox.height / 2); label.children[1].setAttribute('width', bbox.width); label.children[1].setAttribute('height', bbox.height); label.children[2].children[0].style.fontSize = copiedElement.children[2].children[0].style.fontSize; label.children[2].children[0].height = bbox.height; label.children[0].setAttribute('pointer-event', 'all'); updateLabel(label); currentMatrix = getMatrix(selectedElement); displayInfo(label); } } }; /** * Clear svg of mouse events */ var clearSVGEvents = function(){ svg.removeAttribute("onmousemove"); svg.removeAttribute("onmouseup"); svg.removeAttribute("onmouseout"); }; /** * Clear editing phase */ var clearEdit = function(){ if (editing) { editing = false; if (currentEditTarget) { currentEditTarget.hide(); currentEditTarget.prev().show(); currentEditTarget = 0; } if (isLabel(selectedElement) && selectedEditBox) { endLabelEdit(); } } }; // copy paste events $(document).bind('copy', function () { copySelectedElement(); }); $(document).bind('paste', function () { pasteSelectedElement(); }); $(document).bind('keydown.meta_s', function () { alert('save'); }); // Called when delete key is pressed by user $('html').keyup(function (e) { if (!editing) { if (e.keyCode == 46 || e.keyCode == 8) { if (selectedElement != 0) { if (isNode(selectedElement)) { svg.removeChild(selectedElement); deleteVertex(selectedElement.getAttribute('id')); } else if (isEdge(selectedElement)) { svg.removeChild(selectedElement.parentElement); deleteEdge(selectedElement.getAttribute('v1'), selectedElement.getAttribute('v2')); } else if (isLabel(selectedElement)) { svg.removeChild(selectedElement); } displayBoard(); selectedElement = 0; } } } if (forceAlign) { forceAlign = false; } }); // Called when enter key is pressed by user $('html').keyup(function (e) { if (e.keyCode == 13) { if (isLabel(selectedElement) && editing) { endLabelEdit(); } } }); // force align $('html').keydown(function (e) { if (e.keyCode == 65) { forceAlign = true; } });<file_sep>/app/graph.js /** * @author tpan496 * Script that deals with graph-related manipulations. */ var svg; var V = []; var E = []; var E_in = []; var E_out = []; var vacantPositions = []; var E_shape = []; /** * Returns a reusable serial id. If there is no reusable one, * return -1. */ var getReusableId = function () { if (vacantPositions.length > 0) { return vacantPositions.pop(); } else { return -1; } }; /** * Adds a new graph node(vertex) * @param {serial id} v * @param {node object} node */ var addVertex = function (v, node) { while (V.length <= v) { V.push(-1); E.push([]); E_in.push([]); E_out.push([]); E_shape.push([]); } V[v] = node; }; /** * Adds a new edge * @param {out vertex} u * @param {in vertex} v * @param {edge object} line */ var addEdge = function (u, v, line) { E[u].push(v); E[v].push(u); E_shape[u].push(line); E_shape[v].push(line); E_out[u].push(v); E_in[v].push(u); console.log([u, v]); console.log(E_out); }; /** * Returns all the edges of a vertex * @param {vertex} v */ var getEdges = function (v) { return E_shape[v]; }; /** * Removes a vertex from graph * @param {vertex} v */ var deleteVertex = function (v) { V[v] = -1; var degV = E[v].length; for (i = 0; i < degV; i++) { var u = E[v][i]; var degU = E[u].length; var outDegU = E_out[u].length; var inDegU = E_in[u].length; for (j = 0; j < degU; j++) { if (E[u][j] == v) { E[u].splice(j, 1); E_shape[u].splice(j, 1); console.log("delete " + v + " from " + u); console.log(u + ": " + E[u]); break; } } for (j = 0; j < outDegU; j++) { if (E_out[u][j] == v) { E_out[u].splice(j, 1); break; } } for (j = 0; j < inDegU; j++) { if (E_in[u][j] == v) { E_in[u].splice(j, 1); break; } } svg.removeChild(E_shape[v][i]); } E[v] = []; E_shape[v] = []; E_out[v] = []; E_in[v] = []; V[v] = 0; vacantPositions.push(v); }; /** * Deletes an edge from the graph * @param {out vertex} u * @param {in vertex} v */ var deleteEdge = function (u, v) { console.log(E_out); var degU = E[u].length; var degV = E[v].length; for (i = 0; i < degV; i++) { if (E[v][i] == u) { E[v].splice(i, 1); E_shape[v].splice(i, 1); break; } } for (i = 0; i < degU; i++) { if (E[u][i] == v) { E[u].splice(i, 1); E_shape[u].splice(i, 1); break; } } var outDegU = E_out[u].length; var inDegV = E_in[v].length; for (i = 0; i < outDegU; i++) { if (E_out[u][i] == v) { E_out[u].splice(i, 1); break; } } for (i = 0; i < inDegV; i++) { if (E_in[v][i] == u) { E_in[v].splice(i, 1); break; } } console.log(E_out); }; /** * Generates a new graph from loaded xml file */ var generateGraphFromXml = function () { E = []; E_out = []; E_in = []; E_shape = []; vacantPositions = []; V = []; for (child of svg.children) { if (isNode(child)) { var id = child.getAttribute('id'); addVertex(id, child); } } var isDirected = true; var findEdge = false; for (child of svg.children) { if (isEdge(child.children[0])) { var u = child.children[0].getAttribute('v1'); var v = child.children[0].getAttribute('v2'); addEdge(u, v, child); if(!findEdge && child.children[1].getAttribute('visibility') == 'hidden'){ isDirected = false; } findEdge = true; } } var max = 0; for (i = 0; i < V.length; i++) { if (V[i] == -1) { vacantPositions.push(i); } else { if (max < i) { max = i; } } } serialId = max + 1; if(isDirected){ if(!directedOn){ toggleDirected($('#directed')); } }else{ if(directedOn){ toggleDirected($('#directed')); } } };<file_sep>/app/scale.js /** * @author tpan496 * Contains two scripts that deal with object * scaling. */ /** * Deals with node scaling by scaler node. * @param {horizontal mouse movement distance} dx * @param {vertical mouse movement distance} dy */ var scale = function (dx, dy) { if (!isNode(selectedElement)) { return; } var radius = getRadius(selectedElement); var diff = Math.sqrt(dx * dx + dy * dy); var mutator = selectedElement.children[2]; // change linker position var linker = mutator.children[1]; var linkerMatrix = getMatrix(linker); linkerMatrix[4] = getAbsoluteX(linker) + dx / 2; linkerMatrix[5] = getAbsoluteY(linker) + dy / 2; newMatrix = matrixToString(linkerMatrix); linker.setAttribute('transform', newMatrix); updateXY(linker, dx / 2, dy / 2); // change circle scale and position var circle = selectedElement.children[0]; // change circle and node position as well updateXY(circle, dx / 2, dy / 2); updateXY(selectedElement, dx / 2, dy / 2); displayXY(selectedElement); // change text position var text = selectedElement.children[1]; var textMatrix = getMatrix(text); textMatrix[4] = getAbsoluteX(text) + dx / 2; textMatrix[5] = getAbsoluteY(text) + dy / 2; newMatrix = matrixToString(textMatrix); text.setAttribute('transform', newMatrix); updateXY(text, dx / 2, dy / 2); var circleMatrix = getMatrix(circle); // change scaler position var scaler = mutator.children[0]; // check which is current scaler var scalerNE = scaler.children[2]; var scalerSE = scaler.children[0]; var scalerNW = scaler.children[1]; var scalerSW = scaler.children[3]; var scalerId = selectedScaler.getAttribute('id'); var lineN = scaler.children[4]; var lineW = scaler.children[5]; var lineE = scaler.children[6]; var lineS = scaler.children[7]; if (scalerId == 'nw') { var rate = (getRadius(circle) - dx / 2) / getBaseRadius(circle); circleMatrix[0] = rate; circleMatrix[3] = rate; circleMatrix[4] = getAbsoluteX(circle) + dx / 2; circleMatrix[5] = getAbsoluteY(circle) + dy / 2; newMatrix = matrixToString(circleMatrix); circle.setAttribute('transform', newMatrix); updateRadius(circle, -dx / 2); // change loop and terminal var loop = selectedElement.children[3]; updateHalfCircle(selectedElement, loop, getX(circle), getY(circle), getRadius(selectedElement.children[0])); var terminal = selectedElement.children[4]; var terminalMatrix = getMatrix(terminal); terminalMatrix[0] = rate; terminalMatrix[3] = rate; terminalMatrix[4] = getAbsoluteX(circle) + dx / 2; terminalMatrix[5] = getAbsoluteY(circle) + dy / 2; newMatrix = matrixToString(terminalMatrix); terminal.setAttribute('transform', newMatrix); updateRadius(terminal, -dx / 2); var swMatrix = getMatrix(scalerSW); swMatrix[4] = getAbsoluteX(scalerSW) + dx; scalerSW.setAttribute('transform', matrixToString(swMatrix)); updateXY(scalerSW, dx, 0); var neMatrix = getMatrix(scalerNE); neMatrix[5] = getAbsoluteY(scalerNE) + dy; scalerNE.setAttribute('transform', matrixToString(neMatrix)); updateXY(scalerNE, 0, dy); var nMatrix = getMatrix(lineN); nMatrix[4] = getAbsoluteX(lineN) + dx / 2; nMatrix[5] = getAbsoluteY(lineN) + dy; nMatrix[0] = rate; nMatrix[3] = rate; lineN.setAttribute('transform', matrixToString(nMatrix)); updateXY(lineN, dx / 2, dy); var wMatrix = getMatrix(lineW); wMatrix[4] = getAbsoluteX(lineW) + dx; wMatrix[5] = getAbsoluteY(lineW) + dy / 2; wMatrix[0] = rate; wMatrix[3] = rate; lineW.setAttribute('transform', matrixToString(wMatrix)); updateXY(lineW, dx, dy / 2); var sMatrix = getMatrix(lineS); sMatrix[4] = getAbsoluteX(lineS) + dx / 2; sMatrix[0] = rate; sMatrix[3] = rate; lineS.setAttribute('transform', matrixToString(sMatrix)); updateXY(lineS, dx / 2, 0); var eMatrix = getMatrix(lineE); eMatrix[5] = getAbsoluteY(lineE) + dy / 2; eMatrix[0] = rate; eMatrix[3] = rate; lineE.setAttribute('transform', matrixToString(eMatrix)); updateXY(lineE, 0, dy / 2); } else if (scalerId == 'ne') { var rate = (getRadius(circle) + dx / 2) / getBaseRadius(circle); circleMatrix[0] = rate; circleMatrix[3] = rate; circleMatrix[4] = getAbsoluteX(circle) + dx / 2; circleMatrix[5] = getAbsoluteY(circle) + dy / 2; newMatrix = matrixToString(circleMatrix); circle.setAttribute('transform', newMatrix); updateRadius(circle, dx / 2); // change loop and terminal var loop = selectedElement.children[3]; updateHalfCircle(selectedElement, loop, getX(circle), getY(circle), getRadius(selectedElement.children[0])); var terminal = selectedElement.children[4]; var terminalMatrix = getMatrix(terminal); terminalMatrix[0] = rate; terminalMatrix[3] = rate; terminalMatrix[4] = getAbsoluteX(circle) + dx / 2; terminalMatrix[5] = getAbsoluteY(circle) + dy / 2; newMatrix = matrixToString(terminalMatrix); terminal.setAttribute('transform', newMatrix); updateRadius(terminal, dx / 2); var nwMatrix = getMatrix(scalerNW); nwMatrix[5] = getAbsoluteY(scalerNW) + dy; scalerNW.setAttribute('transform', matrixToString(nwMatrix)); updateXY(scalerNW, 0, dy); var seMatrix = getMatrix(scalerSE); seMatrix[4] = getAbsoluteX(scalerSE) + dx; scalerSE.setAttribute('transform', matrixToString(seMatrix)); updateXY(scalerSE, dx, 0); var nMatrix = getMatrix(lineN); nMatrix[4] = getAbsoluteX(lineN) + dx / 2; nMatrix[5] = getAbsoluteY(lineN) + dy; nMatrix[0] = rate; nMatrix[3] = rate; lineN.setAttribute('transform', matrixToString(nMatrix)); updateXY(lineN, dx / 2, dy); var wMatrix = getMatrix(lineW); wMatrix[5] = getAbsoluteY(lineW) + dy / 2; wMatrix[0] = rate; wMatrix[3] = rate; lineW.setAttribute('transform', matrixToString(wMatrix)); updateXY(lineW, 0, dy / 2); var sMatrix = getMatrix(lineS); sMatrix[4] = getAbsoluteX(lineS) + dx / 2; sMatrix[0] = rate; sMatrix[3] = rate; lineS.setAttribute('transform', matrixToString(sMatrix)); updateXY(lineS, dx / 2, 0); var eMatrix = getMatrix(lineE); eMatrix[4] = getAbsoluteX(lineE) + dx; eMatrix[5] = getAbsoluteY(lineE) + dy / 2; eMatrix[0] = rate; eMatrix[3] = rate; lineE.setAttribute('transform', matrixToString(eMatrix)); updateXY(lineE, dx, dy / 2); } else if (scalerId == 'se') { var rate = (getRadius(circle) + dx / 2) / getBaseRadius(circle); circleMatrix[0] = rate; circleMatrix[3] = rate; circleMatrix[4] = getAbsoluteX(circle) + dx / 2; circleMatrix[5] = getAbsoluteY(circle) + dy / 2; newMatrix = matrixToString(circleMatrix); circle.setAttribute('transform', newMatrix); updateRadius(circle, dx / 2); // change loop and terminal var loop = selectedElement.children[3]; updateHalfCircle(selectedElement, loop, getX(circle), getY(circle), getRadius(selectedElement.children[0])); var terminal = selectedElement.children[4]; var terminalMatrix = getMatrix(terminal); terminalMatrix[0] = rate; terminalMatrix[3] = rate; terminalMatrix[4] = getAbsoluteX(circle) + dx / 2; terminalMatrix[5] = getAbsoluteY(circle) + dy / 2; newMatrix = matrixToString(terminalMatrix); terminal.setAttribute('transform', newMatrix); updateRadius(terminal, dx / 2); var swMatrix = getMatrix(scalerSW); swMatrix[5] = getAbsoluteY(scalerSW) + dy; scalerSW.setAttribute('transform', matrixToString(swMatrix)); updateXY(scalerSW, 0, dy); var neMatrix = getMatrix(scalerNE); neMatrix[4] = getAbsoluteX(scalerNE) + dx; scalerNE.setAttribute('transform', matrixToString(neMatrix)); updateXY(scalerNE, dx, 0); var nMatrix = getMatrix(lineN); nMatrix[4] = getAbsoluteX(lineN) + dx / 2; nMatrix[0] = rate; nMatrix[3] = rate; lineN.setAttribute('transform', matrixToString(nMatrix)); updateXY(lineN, dx / 2, 0); var wMatrix = getMatrix(lineW); wMatrix[5] = getAbsoluteY(lineW) + dy / 2; wMatrix[0] = rate; wMatrix[3] = rate; lineW.setAttribute('transform', matrixToString(wMatrix)); updateXY(lineW, 0, dy / 2); var sMatrix = getMatrix(lineS); sMatrix[4] = getAbsoluteX(lineS) + dx / 2; sMatrix[5] = getAbsoluteY(lineS) + dy; sMatrix[0] = rate; sMatrix[3] = rate; lineS.setAttribute('transform', matrixToString(sMatrix)); updateXY(lineS, dx / 2, dy); var eMatrix = getMatrix(lineE); eMatrix[4] = getAbsoluteX(lineE) + dx; eMatrix[5] = getAbsoluteY(lineE) + dy / 2; eMatrix[0] = rate; eMatrix[3] = rate; lineE.setAttribute('transform', matrixToString(eMatrix)); updateXY(lineE, dx, dy / 2); } else if (scalerId == 'sw') { var rate = (getRadius(circle) - dx / 2) / getBaseRadius(circle); circleMatrix[0] = rate; circleMatrix[3] = rate; circleMatrix[4] = getAbsoluteX(circle) + dx / 2; circleMatrix[5] = getAbsoluteY(circle) + dy / 2; newMatrix = matrixToString(circleMatrix); circle.setAttribute('transform', newMatrix); updateRadius(circle, -dx / 2); // change loop and terminal var loop = selectedElement.children[3]; updateHalfCircle(selectedElement, loop, getX(circle), getY(circle), getRadius(selectedElement.children[0])); var terminal = selectedElement.children[4]; var terminalMatrix = getMatrix(terminal); terminalMatrix[0] = rate; terminalMatrix[3] = rate; terminalMatrix[4] = getAbsoluteX(circle) + dx / 2; terminalMatrix[5] = getAbsoluteY(circle) + dy / 2; newMatrix = matrixToString(terminalMatrix); terminal.setAttribute('transform', newMatrix); updateRadius(terminal, -dx / 2); var nwMatrix = getMatrix(scalerNW); nwMatrix[4] = getAbsoluteX(scalerNW) + dx; scalerNW.setAttribute('transform', matrixToString(nwMatrix)); updateXY(scalerNW, dx, 0); var seMatrix = getMatrix(scalerSE); seMatrix[5] = getAbsoluteY(scalerSE) + dy; scalerSE.setAttribute('transform', matrixToString(seMatrix)); updateXY(scalerSE, 0, dy); var nMatrix = getMatrix(lineN); nMatrix[4] = getAbsoluteX(lineN) + dx / 2; nMatrix[0] = rate; nMatrix[3] = rate; lineN.setAttribute('transform', matrixToString(nMatrix)); updateXY(lineN, dx / 2, 0); var wMatrix = getMatrix(lineW); wMatrix[4] = getAbsoluteX(lineW) + dx; wMatrix[5] = getAbsoluteY(lineW) + dy / 2; wMatrix[0] = rate; wMatrix[3] = rate; lineW.setAttribute('transform', matrixToString(wMatrix)); updateXY(lineW, dx, dy / 2); var sMatrix = getMatrix(lineS); sMatrix[4] = getAbsoluteX(lineS) + dx / 2; sMatrix[5] = getAbsoluteY(lineS) + dy; sMatrix[0] = rate; sMatrix[3] = rate; lineS.setAttribute('transform', matrixToString(sMatrix)); updateXY(lineS, dx / 2, dy); var eMatrix = getMatrix(lineE); eMatrix[5] = getAbsoluteY(lineE) + dy / 2; eMatrix[0] = rate; eMatrix[3] = rate; lineE.setAttribute('transform', matrixToString(eMatrix)); updateXY(lineE, 0, dy / 2); } radiusInfo.html(getRadius(circle)); }; /** * Deals with scaling to a specific radius with the * position untouched. * @param {new radius} targetRadius */ var scaleTo = function (targetRadius) { if (!isNode(selectedElement)) { return; } var mutator = selectedElement.children[2]; var circle = selectedElement.children[0]; var circleMatrix = getMatrix(circle); // change scaler position var scaler = mutator.children[0]; // check which is current scaler var scalerNE = scaler.children[2]; var scalerSE = scaler.children[0]; var scalerNW = scaler.children[1]; var scalerSW = scaler.children[3]; var lineN = scaler.children[4]; var lineW = scaler.children[5]; var lineE = scaler.children[6]; var lineS = scaler.children[7]; var dr = parseFloat(targetRadius) - getRadius(circle); var rate = parseFloat(targetRadius) / getBaseRadius(circle); circleMatrix[0] = rate; circleMatrix[3] = rate; newMatrix = matrixToString(circleMatrix); circle.setAttribute('transform', newMatrix); updateRadius(circle, dr); var swMatrix = getMatrix(scalerSW); swMatrix[4] = getAbsoluteX(scalerSW) - dr; swMatrix[5] = getAbsoluteY(scalerSW) + dr; scalerSW.setAttribute('transform', matrixToString(swMatrix)); updateXY(scalerSW, -dr, dr); var nwMatrix = getMatrix(scalerNW); nwMatrix[4] = getAbsoluteX(scalerNW) - dr; nwMatrix[5] = getAbsoluteY(scalerNW) - dr; scalerNW.setAttribute('transform', matrixToString(nwMatrix)); updateXY(scalerNW, -dr, -dr); var neMatrix = getMatrix(scalerNE); neMatrix[4] = getAbsoluteX(scalerNE) + dr; neMatrix[5] = getAbsoluteY(scalerNE) - dr; scalerNE.setAttribute('transform', matrixToString(neMatrix)); updateXY(scalerNE, dr, -dr); var seMatrix = getMatrix(scalerSE); seMatrix[4] = getAbsoluteX(scalerSE) + dr; seMatrix[5] = getAbsoluteY(scalerSE) + dr; scalerSE.setAttribute('transform', matrixToString(seMatrix)); updateXY(scalerSE, dr, dr); var nMatrix = getMatrix(lineN); nMatrix[5] = getAbsoluteY(lineN) - dr; nMatrix[0] = rate; nMatrix[3] = rate; lineN.setAttribute('transform', matrixToString(nMatrix)); updateXY(lineN, 0, -dr); var wMatrix = getMatrix(lineW); wMatrix[4] = getAbsoluteX(lineW) - dr; wMatrix[0] = rate; wMatrix[3] = rate; lineW.setAttribute('transform', matrixToString(wMatrix)); updateXY(lineW, -dr, 0); var sMatrix = getMatrix(lineS); sMatrix[5] = getAbsoluteY(lineS) + dr; sMatrix[0] = rate; sMatrix[3] = rate; lineS.setAttribute('transform', matrixToString(sMatrix)); updateXY(lineS, 0, dr); var eMatrix = getMatrix(lineE); eMatrix[4] = getAbsoluteX(lineE) + dr; eMatrix[0] = rate; eMatrix[3] = rate; lineE.setAttribute('transform', matrixToString(eMatrix)); updateXY(lineE, dr, 0); var loop = selectedElement.children[3]; updateHalfCircle(selectedElement, loop, getX(circle), getY(circle), getRadius(selectedElement.children[0])); var terminal = selectedElement.children[4]; var terminalMatrix = getMatrix(terminal); terminalMatrix[0] = rate; terminalMatrix[3] = rate; newMatrix = matrixToString(terminalMatrix); terminal.setAttribute('transform', newMatrix); updateRadius(terminal, dr); };
ec52b2a696e45c7bf7a813c08dfb19ca60cff9be
[ "JavaScript", "Markdown" ]
8
JavaScript
fauzirifky/csgraph_editor
18d0594b0ac7d5bf76afec4177ba0b287d7e3f24
feeef3f755bbe6be6ce8a94878106e37b8acba88
refs/heads/development
<repo_name>NiiazalyDzhumaliev/bookstore<file_sep>/src/components/App.js import BookList from '../containers/BookList'; import BooksForm from '../containers/BooksForm'; import Header from './Header'; import styles from './App.module.css'; function App() { return ( <div className={styles.app}> <div className={styles.panel_main}> <Header /> <BookList /> <BooksForm /> </div> </div> ); } export default App; <file_sep>/src/components/CategoryFilter.js import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { CHANGE_FILTER } from '../actions'; import styles from './CategoryFilter.module.css'; const { v4: UuidV4 } = require('uuid'); const CategoryFilter = props => { const { onChangeFilter, filter } = props; const handleFilterChange = event => { const { target: { value }, } = event; onChangeFilter(value); }; const categories = [ 'Action', 'Biography', 'History', 'Horror', 'Kids', 'Learning', 'Sci-Fi', ]; return ( <select id="filter-categories" className={styles.category_select} name="category" onChange={handleFilterChange} value={filter} > <option value="" key={UuidV4()}> {'categories'.toUpperCase()} </option> {categories.map(category => ( <option value={category} key={UuidV4()}> {category} </option> ))} </select> ); }; const mapStateToProps = state => ({ filter: state.filt.filter, }); const mapDispatchToProps = dispatch => ({ onChangeFilter: bookCategory => dispatch(CHANGE_FILTER(bookCategory)), }); CategoryFilter.propTypes = { onChangeFilter: PropTypes.func.isRequired, filter: PropTypes.string.isRequired, }; export default connect(mapStateToProps, mapDispatchToProps)(CategoryFilter); <file_sep>/src/reducers/books.js const CREATE_BOOK = 'CREATE_BOOK'; const REMOVE_BOOK = 'REMOVE_BOOK'; const { v4: UuidV4 } = require('uuid'); const initialState = { books: [ { id: UuidV4(), title: '<NAME>', category: 'Kids' }, { id: UuidV4(), title: 'Dzhamilya', category: 'History' }, ], }; const reducer = (state = initialState, action) => { switch (action.type) { case CREATE_BOOK: return { ...state, books: state.books.concat({ id: UuidV4(), title: action.title, category: action.category, }), }; case REMOVE_BOOK: { const updatedArray = state.books.filter(book => book.id !== action.delId); return { ...state, books: updatedArray, }; } default: return state; } }; export default reducer; <file_sep>/src/containers/BookList.js import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import Book from '../components/Book'; import { REMOVE_BOOK } from '../actions'; const { v4: UuidV4 } = require('uuid'); const BookList = props => { const { books, filter, onDeleteBook } = props; const handleClick = bookId => { onDeleteBook(bookId); }; return ( <div> {books .filter( book => filter === 'All' || filter === '' || book.category === filter, ) .map(book => ( <Book bookObject={book} key={UuidV4()} handleClick={() => handleClick(book.id)} /> ))} </div> ); }; const mapStateToProps = state => ({ books: state.bks.books, filter: state.filt.filter, }); const mapDispatchToProps = dispatch => ({ onDeleteBook: bookId => dispatch(REMOVE_BOOK(bookId)), }); BookList.propTypes = { books: PropTypes.arrayOf(PropTypes.object).isRequired, filter: PropTypes.string.isRequired, onDeleteBook: PropTypes.func.isRequired, }; export default connect(mapStateToProps, mapDispatchToProps)(BookList); <file_sep>/src/actions/index.js export const CREATE_BOOK = bookObject => ({ ...bookObject, type: 'CREATE_BOOK', }); export const REMOVE_BOOK = bookId => ({ type: 'REMOVE_BOOK', delId: bookId, }); export const CHANGE_FILTER = bookCategory => ({ type: 'CHANGE_FILTER', category: bookCategory, }); <file_sep>/src/components/Book.js import PropTypes from 'prop-types'; import styles from './Book.module.css'; const Book = props => { const { bookObject, handleClick } = props; return ( <div className={styles.book_container}> <div className={styles.book_info}> <p className={styles.category}>{bookObject.category}</p> <p className={styles.title}>{bookObject.title}</p> <p className={styles.author}>Author</p> <button type="button" className={styles.button}> Comment </button> <button type="button" onClick={handleClick} className={styles.button} id={styles.delete} > Delete </button> <button type="button" className={styles.button} id={styles.edit}> Edit </button> </div> <div className={styles.progress_container}> <div className={styles.completed_container}> <p className={styles.circle} /> <div> <p className={styles.percent}>78%</p> <p className={styles.completed}>Completed</p> </div> </div> <div className={styles.chapter_container}> <p className={styles.current_chapter}> {'current chapter'.toUpperCase()} </p> <p className={styles.chapter}>Chapter 17</p> <button type="button" className={styles.update_progress}> {'update progress'.toUpperCase()} </button> </div> </div> </div> ); }; Book.propTypes = { bookObject: PropTypes.objectOf(PropTypes.any).isRequired, handleClick: PropTypes.func.isRequired, }; export default Book; <file_sep>/src/components/Header.js import { ReactComponent as Logo } from '../icons/user.svg'; import styles from './Header.module.css'; import CategoryFilter from './CategoryFilter'; const Header = () => ( <div className={styles.header_container}> <div className={styles.bookstore_container}> <span className={styles.bookstore}>BookStore CMS</span> <span className={styles.books}>{'Books'.toUpperCase()}</span> <CategoryFilter /> </div> <div> <Logo fill="#0290ff" className={styles.user} /> </div> </div> ); export default Header;
1b2e5c46bf39c54258e5ff46c8e4d70453c47227
[ "JavaScript" ]
7
JavaScript
NiiazalyDzhumaliev/bookstore
d7522b2899cc6e9f275ab1f8a38be548bb1f114e
f678f9c57a9921034e3eb3564842773ce6833316
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Registro_Productos.BD { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btningresar_Click(object sender, EventArgs e) { Productos Productos = new Productos(); Productos.id_producto = Convert.ToInt32(txtid_producto.Text); Productos.nombre = txtnombre.Text; Productos.descripcion = txtdescripcion.Text; Productos.cantidad = Convert.ToInt32(txtcantidad.Text); int resultado = ProductosDA.Agregar(Productos); if (resultado > 0) { MessageBox.Show("Datos Guardados Correctamente", "Datos Guardados",MessageBoxButtons.OK,MessageBoxIcon.Information); } else { MessageBox.Show("No se Puedieron Guardar los Datos", "Error al Guardar", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } private void Form1_Load(object sender, EventArgs e) { } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace Registro_Productos.BD { public class ProductosDA { public static int Agregar(Productos pProductos) { int retorno = 0; using (SqlConnection Conn = Conexion.ObtenerConexion()) { SqlCommand Comando = new SqlCommand(string.Format("Insert Into producto (id_producto, nombre, descripcion, cantidad) values ('{0}','{1}','{2}','{3}')", pProductos.id_producto, pProductos.nombre, pProductos.descripcion, pProductos.cantidad), Conn); retorno = Comando.ExecuteNonQuery(); } return retorno; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace Registro_Productos.BD { public class Conexion { public static SqlConnection ObtenerConexion(){ SqlConnection Conn = new SqlConnection("Data source=SEBASTIAN;Initial Catalog=productos; User Id=enspdf; Password=123"); Conn.Open(); return Conn; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Registro_Productos.BD { public class Productos { public int id_producto { get; set; } public String nombre { get; set; } public String descripcion { get; set; } public int cantidad { get; set; } public Productos() { } public Productos(int pid_producto, String pnombre, String pdescripcion, int pcantidad) { this.id_producto = pid_producto; this.nombre = pnombre; this.descripcion = pdescripcion; this.cantidad = pcantidad; } } } <file_sep>App_productos ============= App_productos
9d323df72c27f25c2bc9b040fdb7e3a1376ef344
[ "Markdown", "C#" ]
5
C#
enspdf/App_productos
ee1362937f82b0e22b37925cb51447562aa95369
cbf31c2e15caccaa846c085753158333deb98f01
refs/heads/master
<file_sep>#!/usr/bin/env python import logging import custom_logging from features_fetcher import FeaturesFetcher from redis_interface import RedisInterface from dooino import Dooino logger = logging.getLogger(__name__) class Setup(RedisInterface): REDIS_KEY = "dooinos" def __init__(self, name, ip): logger.info("Setting up dooino") self.name = name self.ip = ip def register(self): dooino = Dooino(self.name) dooino.set("ip", self.ip) features = FeaturesFetcher(dooino) features.fetch() dooino.destroy() dooino = Dooino(features.data["id"]) dooino.register() dooino.set("ip", self.ip) dooino.fetch() def destroy(self): self.redis.srem(self.REDIS_KEY, self.name) self.redis.delete(self.name) <file_sep>import logging LOG_FILENAME = "log.log" logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,format="%(asctime)s %(levelname)s - (%(funcName)s) - %(message)s") <file_sep>#!/usr/bin/env python import logging import redis import custom_logging logger = logging.getLogger(__name__) class DooinoList: REDIS_KEY = "dooinos" def __init__(self): self.redis = redis.StrictRedis(host="localhost", port=6379, db=0) def run(self): return self.redis.smembers("dooinos") <file_sep>#!/usr/bin/env python from flask import Flask from flask import render_template from flask import request from flask import jsonify app = Flask(__name__) @app.route("/status") def status(): return jsonify({'value': 10}) @app.route("/on") def on(): return jsonify({}) @app.route("/off") def off(): return jsonify({}) @app.route("/manifest.json") def fake(): return jsonify( { 'name': 'dooino-xyz', 'ip': '127.0.0.1', 'in': [ { 'name': 'on', 'action': 'http://127.0.0.1:6000/on' }, { 'name': 'off', 'action': 'http://127.0.0.1:6000/off' } ], 'out': [ { 'name': 'status', 'action': 'http://127.0.0.1:6000/status' } ], 'version': 123, 'capabilities': [], }) if __name__ == "__main__": app.run(host= '0.0.0.0',port=6000) <file_sep>#!/usr/bin/env python import requests import logging logger = logging.getLogger(__name__) class FeaturesFetcher: def __init__(self, dooino): self.dooino = dooino self.data = {} def fetch(self): if self.dooino.get("ip") is None: logger.error("URL is None") return url = self.dooino.manifest_url() logger.info("Requesting URL: %s", url) try: data = requests.get(url, timeout=1).json() self.data = data self.dooino.touch() logger.info("Fetched data: %s", data) except Exception: self.dooino.take_offline() logger.fatal("Could not connect", exc_info=True) <file_sep>#!/usr/bin/env python import logging import redis import json import custom_logging from routine import Routine logger = logging.getLogger(__name__) class RoutineList: REDIS_KEY = "routines" def __init__(self): self.redis = redis.StrictRedis(host="localhost", port=6379, db=0) def run(self): data = [] for routine in self.redis.smembers(self.REDIS_KEY): data.append(json.loads(routine)) return data <file_sep>#!/usr/bin/env python import redis class RedisInterface: def __init__(self): self.redis = redis.StrictRedis(host="localhost", port=6379, db=0) self.name = "DEFAULT" def set(self, name, value): self.redis.hset(self.name, name, value) def get(self, name, value): self.redis.hset(self.name, name, value) <file_sep>#!/usr/bin/env python import logging import json import redis import custom_logging logger = logging.getLogger(__name__) class Routine: REDIS_KEY = "routines" def __init__(self, data): self.data = data self.redis = redis.StrictRedis(host="localhost", port=6379, db=0) def save(self): self.redis.sadd(self.REDIS_KEY, json.dumps(self.data)) <file_sep>#!/usr/bin/env python import logging import json import datetime import redis import custom_logging from features_fetcher import FeaturesFetcher logger = logging.getLogger(__name__) class Dooino: REDIS_KEY = "dooinos" def __init__(self, _id): logger.info("Loading dooino") self.id = _id self.redis = redis.StrictRedis(host="localhost", port=6379, db=0) def set(self, name, value): self.redis.hset(self.id, name, value) def get(self, name): return self.redis.hget(self.id, name) def ins(self): return json.loads(self.get("in")) def outs(self): return json.loads(self.get("out")) def get_in_action(self, name): action = None for _in in self.ins(): if _in["name"] == name: action = _in["action"] return action def get_out_action(self, name): action = None for out in self.outs(): if out["name"] == name: action = out["action"] return action def manifest_url(self): return "http://" + self.get("ip") + "/manifest.json" def touch(self): self.set("updated_at", datetime.datetime.now()) self.set("online", 1) def register(self): self.redis.sadd(self.REDIS_KEY, self.id) def fetch(self): features = FeaturesFetcher(self) features.fetch() for key in features.data: if key == "in" or key == "out": self.set(key, json.dumps(features.data[key])) else: self.set(key, features.data[key]) return features.data def serialize(self): data = {} remote_data = self.fetch() local_data = self._serialize() data.update(local_data) data.update(remote_data) for key in data: if data[key] == "1": data[key] = True elif data[key] == "0": data[key] = False return data def _serialize(self): data = {} for key in self.redis.hkeys(self.id): data[key] = self.get(key) return data def online(self): return self.get("online") def take_offline(self): self.set("online", 0) def destroy(self): self.redis.srem(self.REDIS_KEY, self.id) self.redis.delete(self.id) <file_sep>#!/usr/bin/env python import logging import custom_logging from flask import Flask from flask import render_template from flask import jsonify from flask import request from dooino import Dooino from dooino_list import DooinoList from routine import Routine from routine_list import RoutineList app = Flask(__name__) logger = logging.getLogger(__name__) @app.route("/") def dashboard(): return render_template('application.html') @app.route("/new") def new(): return render_template('application.html') @app.route("/routines", methods=['POST', 'GET']) def routines(): if request.method == 'POST': params = request.get_json() data = {} for key in params: data[key] = params.get(key) Routine(data).save() return jsonify({}) else: return jsonify(RoutineList().run()) @app.route("/dooinos") def dooinos(): data = [] for entry in DooinoList().run(): device = Dooino(entry) data.append(device.serialize()) return jsonify(data) @app.route("/templates/<template>.html") def template(template): return render_template(template + ".html"), 200, {'Content-Type': 'text/plain; charset=utf-8'} if __name__ == "__main__": app.run(host= '0.0.0.0') <file_sep>#!/usr/bin/env python import logging import redis import json import requests import time import os import custom_logging from routine_list import RoutineList from dooino import Dooino logger = logging.getLogger(__name__) class Ping: def __init__(self, host): self.host = host logger.fatal(host) def run(self): ip = self._parse_ip(self.host) response = os.system("ping -c 1 -W 200 " + ip) if response is 0: return True return False def _parse_ip(self, ip): return ip.split(":")[0] class Requester: def __init__(self, source): self.source = source self.dooino = Dooino(source["id"]) def run(self): try: url = self.dooino.get_out_action(self.source["action"]) data = requests.get(url, timeout=1).json() return data["value"] except Exception: logger.fatal("Could not connect", exc_info=True) return None class Executor: def __init__(self, target): self.target = target self.dooino = Dooino(target["id"]) def run(self): try: url = self.dooino.get_in_action(self.target["action"]) requests.get(url, timeout=0.5) except Exception: logger.fatal("Could not execute", exc_info=True) return None class Checker: def __init__(self, output, input, operation): self.output = output self.input = input self.operation = operation def run(self): logger.debug("Checking %s agains %s", self.output, self.input) if self.output == "null" or self.output is None or self.input is None or self.operation is None: return False output = float(self.output) input = float(self.input) operation = int(self.operation) if operation is 0: logger.debug("equal") return output == input elif operation is 1: logger.debug("greater") return output > input elif operation is 2: logger.debug("smaller") return output < input else: logger.debug("operation failed") return False class Processor: def __init__(self, routine): self.routine = routine def run(self): out = Requester(self.routine["source"]).run() operation = self.routine["condition"]["operation"] value = self.routine["condition"]["value"] if Checker(out, value, operation).run(): logger.info("Executing routine...") Executor(self.routine["target"]).run() else: logger.info("Skipping routine...") class PresenceWorker: DOOINOS_KEY = "dooinos" def __init__(self): logger.info("Checking presence of devices...") self.redis = redis.StrictRedis(host='localhost', port=6379, db=0) def run(self): logger.info("Running check...") devices = self.redis.smembers(self.DOOINOS_KEY) keys_to_delete = [] for device in devices: ip = self.redis.get(device) url = "http://" + ip + "/manifest.json" if Ping(ip).run(): logger.info("Device is present: %s(%s)", device, ip) else: keys_to_delete.append(device) logger.fatal("Device is not present", exc_info=True) for key in keys_to_delete: self.redis.srem(self.DOOINOS_KEY, key) class RoutineWorker: def __init__(self): logger.info("Initializing worker...") def run(self): logger.info("Running...") for data in RoutineList().run(): routine = data if self._is_valid_routine(routine): Processor(routine).run() def _is_valid_routine(self, routine): if( routine.get("source", {}).get("id") is None or routine.get("source", {}).get("action") is None or routine.get("target", {}).get("id") is None or routine.get("target", {}).get("action") is None or routine.get("condition", {}).get("value") is None or routine.get("condition", {}).get("operation") is None ): logger.fatal("Could not process routine: %s", routine) return False return True if __name__ == "__main__": LOOP_TIME = 5 while True: # PresenceWorker().run() RoutineWorker().run() time.sleep(LOOP_TIME) <file_sep># Web server configuration ## Dependencies ```bash gem install foreman pip install requests pip install zeroconf pip install flask pip install redis ``` ## Development server ```bash dockup-compose up foreman start ``` ### Register a service locally ```bash python register.py ``` ## Files * `custom_logging.py`: Config for our logger * `discovery.py`: Discovers clients * `docker-compose.yml`: You know... * `fake-response.py`: For developments purposes it fakes a _dooino_ manifest * `features_fetcher.py`: Retrieves the information from the manifests * `Procfile`: Run all the necessary for development * `register.py`: Registers a _dooino_ locally * `server.py`: Web server
99c6503da231181c24be98c39c667c5799d9aba1
[ "Markdown", "Python" ]
12
Python
dooino/web
34a2b1e64ba74c13c5b27f5b749b43cda28003d3
935fb8d083e6ee5bc405f3a2195a85aec65e7ec8